Fill the drop-down list dynamically using Javascript / jQuery

In the ASP.NET MVC Razor view, I have a drop-down list as follows:

@Html.DropDownListFor(model => model.SelectedDeviceModel, Model.DeviceModelList)

DeviceModelList is just a SelectList.

How can I dynamically populate a DeviceModelList depending on the client-side action, for example, by clicking a button or other dropdown using Javascript / jQuery / Ajax?

+5
source share
1 answer

You can select this partial menu in partial:

@model MyViewModel
@Html.DropDownListFor(model => model.SelectedDeviceModel, Model.DeviceModelList)

then in your main view, include it inside some container:

@model MyViewModel
...
<div id="ddlcontainer">
    @Html.Partial("Foo", Model)
</div>
...

, :

public ActionResult Foo(string someValue)
{
    MyViewModel model = ... go ahead and fill your view model
    return PartialView(model);
}

AJAX - . , - ddl ( - , - ):

$(function() {
    $('#SomeOtherDdlId').change(function() {
        // when the selection of some other drop down changes 
        // get the new value
        var value = $(this).val();

        // and send it as AJAX request to the newly created action
        $.ajax({
            url: '@Url.Action("foo")',
            type: 'POST',
            data: { someValue: value },
            success: function(result) {
                // when the AJAX succeeds refresh the ddl container with
                // the partial HTML returned by the Foo controller action
                $('#ddlcontainer').html(result);
            }
        });
    });
});

JSON. Foo Json, /, AJAX . . :

$(function() {
    $('#SomeOtherDdlId').change(function() {
        // when the selection of some other drop down changes 
        // get the new value
        var value = $(this).val();

        // and send it as AJAX request to the newly created action
        $.ajax({
            url: '@Url.Action("foo")',
            type: 'POST',
            data: { someValue: value },
            success: function(result) {
                // when the AJAX succeeds refresh the dropdown list with 
                // the JSON values returned from the controller action
                var selectedDeviceModel = $('#SelectedDeviceModel');
                selectedDeviceModel.empty();
                $.each(result, function(index, item) {
                    selectedDeviceModel.append(
                        $('<option/>', {
                            value: item.value,
                            text: item.text
                        })
                    );
                });
            }
        });
    });
});

, , Foo Json:

public ActionResult Foo(string someValue)
{
    return Json(new[] {
        new { value = '1', text = 'text 1' },
        new { value = '2', text = 'text 2' },
        new { value = '3', text = 'text 3' }
    });
}

.

+11

All Articles