简体   繁体   中英

ASP.net MVC - How to bind and empty dropdownlist to a model on change?

I've two drop down lists on a view. Upon selection in the first list, I'm dynamically populating the second list using ajax call:

$('#NonSelectedCourses').change(function () {
        console.info(this.id.toString());

        var procemessage = "<option value='0'> Please wait...</option>";
        $("#lstSections").html(procemessage).show();

        var option = $(this).find('option:selected').val();
        console.info("List: " + this.id + " Item: " + option);

        //Retreive list for new selection
        var url = '@Url.Content("~/Layout/GetSectionFromCourses")' + '?id=' + option;
        console.info("AJAX Url:" + url);
        $.ajax({ url: url, success: SectionDataRetrieved, type: 'GET', dataType: 'json' });
        });

And a function to populate the other list on successful operation:

function SectionDataRetrieved(data) {            
        var ddl = $('#lstSections');
        ddl.empty();
        $(data.sections).each(function () {
            $(document.createElement('option'))
                .attr('value', this.Value)
                .text(this.Text)
                .appendTo(ddl);                
        });
    }

and a dropdownlist to be populated:

 @Html.DropDownListFor(model => model.sectionList, Enumerable.Empty<SelectListItem>(), "-- Select Sections --", new { id = "lstSections" })

Now, how can I send the data back to the controller. I'm aware of sending it through the Ajax call, but is there a way to bind it back to the ViewModel and send it.

You can do it by setting the name attribute of the DropDownList that will be read by the model binder and bind it to your ViewModel, you just need to match the name attribute of your DDL to your ViewModel property name. Say for example you have a Section property in your ViewModel then you can set the name attribute like below:

SectionDataRetrieved(data) {            
    var ddl = $('#lstSections');
    ddl.empty();
    ddl.attr('name', 'Section');
    $(data.sections).each(function () {
        $(document.createElement('option'))
            .attr('value', this.Value)
            .text(this.Text)
            .appendTo(ddl);                
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM