【问题标题】:ASP.net MVC - How to bind and empty dropdownlist to a model on change?ASP.net MVC - 如何在更改时将下拉列表绑定和清空到模型?
【发布时间】:2016-05-14 02:34:18
【问题描述】:

我在一个视图上有两个下拉列表。在第一个列表中选择后,我使用 ajax 调用动态填充第二个列表:

$('#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' });
        });

还有一个在成功操作时填充另一个列表的函数:

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

以及要填充的下拉列表:

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

现在,如何将数据发送回控制器。我知道通过 Ajax 调用发送它,但是有没有办法将它绑定回 ViewModel 并发送它。

【问题讨论】:

  • 当您提交表单时,您选择的值将绑定到您的sectionList 属性。

标签: ajax asp.net-mvc asp.net-mvc-4 razor


【解决方案1】:

您可以通过设置模型绑定器将读取的 DropDownList 的 name 属性并将其绑定到您的 ViewModel 来实现,您只需要将 DDL 的 name 属性与您的 ViewModel 属性名称相匹配。 例如,假设您的 ViewModel 中有一个 Section 属性,那么您可以设置 name 属性,如下所示:

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);                
    });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-08
    相关资源
    最近更新 更多