MVC 中的空值多选级联下拉列表

Null value multiselect cascading dropdown in MVC

在 MVC 中,我有一个 multiselect 下拉列表 。在更改事件中,我正在填充另一个下拉列表,但无法在 控制器 上获得多个 select 值,下面是我的代码。

查看

@Html.DropDownList("Country", ViewData["country"] as List<SelectListItem>, new {@multiple="multiple", style = "width:250px", @class = "dropdown1" })

Ajax 通话

<script type="text/javascript">
$(document).ready(function () {

    $("#Country").change(function () {

        var abc = $("#Country").val();
        alert(abc);


        $("#State").empty();
        $.ajax({               
            type: 'POST',
            url: '@Url.Action("GetStates")', // we are calling json method
            dataType: 'json',
            //data: { id: $("#Country").val() },
            data: { "CountryId": abc },
            cache: false,
            success: function (states) {
                // states contains the JSON formatted list
                // of states passed from the controller
                $.each(states, function (i, state) {

                    alert(state.Value);
                    $("#State").append('<option value="' + state.Value + '">' + state.Text + '</option>');
                }); // here we are adding option for States
            },
            error: function (ex) {
                alert('Failed to retrieve states.' + ex);
            }
        });
        return false;
    })
});

控制器

public JsonResult GetStates(string CountryId)
   {
      return null;
   }

但我得到的 CountryIdNULL 对于 multi select 下拉列表仅适用于正常下拉列表 我得到的值.

有解决办法吗?

您生成的 <select multiple="multiple"> 会回传一组值,而不是单个值。

因为你在请求中发送一个数组,所以你需要添加 traditional: true ajax 选项

$.ajax({               
    type: 'POST',
    url: '@Url.Action("GetStates")',
    dataType: 'json',
    data: { countryId: $("#Country").val() },
    traditional: true,
    ....

然后更改控制器方法以接受数组

public JsonResult GetStates(string[] CountryId) // or IEnumerable<string> CountryId

请注意,这是有效的,因为如果是一个简单的数组,但在您可能回发复杂对象数组的情况下,那么您将需要使用 contentType: 'application/json; charset=utf-8' 选项并使用 [= 将数据字符串化15=]

旁注;创建<select multiple>的正确方法是使用@Html.ListBoxFor()方法,它添加了multiple="multiple" attribute. In this case, it will work, but in other cases, for example, usingDropDownListFor()in a loop to create a`,它会无法正确绑定,所以我推荐你使用了正确的方法。