Create DropdownList MVC double

0

I'm working on an MVC ASP.Net project and I need to know how I can perform a view with 2 dropdownlist, in which one depends on another, for example.

State and Peoples. Depending on the state you choose then the villages vary, in real time without having to refresh the page.

I would appreciate your input.

    
asked by Roniel Polanco Mejia 10.07.2017 в 14:46
source

1 answer

1

It can be done with an asynchronous call (ajax). if for example you have the cbxEstados y cbxPueblos You must capture the cbxEstados event, the change event to fill the cbxPueblos combo with information, of course you must send the selected value of the combo so that the second is dynamic. To understand it better the following code.

$(function () {
        $("#cbxEstados").change(function () {
            var selectedItem = $(this).val();
            var ddlStates = $("#cbxPueblos");
            $.ajax({
                cache: false,
                type: "POST",
                dataType: "json",
                url: "@(Url.RouteUrl("GetPueblos"))",
                data: { 'cbxEstados':  selectedItem },
                success: function (data) {
                    ddlStates.html('');
                    $.each(data, function (id, option) {
                        ddlStates.append($('<option></option>').val(option.Value).html(option.Text));
                    });
                    $("#cbxPueblos").val(data2);
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    alert('Failed to retrieve states.');
                }
            });
        });
   });

The GetPueblos method must be declared in your controller depending on how you define your comboBox; that is, if you define it as a model as a list of ComboBox objects for example, the method will have to return a list.

 [HttpPost]
    public async Task<ActionResult> GetPueblos(int cbxEstados) 
    {

        List<ModelComboBox> result = new List<ModelComboBox>();
        result.add(new ModelComboBox{Value ="1", Text ="PUEBLO1"});
        result.add(new ModelComboBox{Value ="2", Text ="PUEBLO2"});
        result.add(new ModelComboBox{Value ="3", Text ="PUEBLO3"});

        return Json(result, JsonRequestBehavior.AllowGet);
    }

And the ModelComboBox class would be the following

public class ModelComboBox
    {
        public string Value { get; set; }
        public string Text { get; set; }
   }
    
answered by 10.07.2017 / 16:00
source