【问题标题】:Null value multiselect cascading dropdown in MVCMVC中的空值多选级联下拉菜单
【发布时间】:2016-05-23 11:28:13
【问题描述】:

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

查看

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

但我将 CountryId 设为 NULL 用于多选下拉案例,仅适用于普通下拉,我得到了值。

有解决办法吗?

【问题讨论】:

  • 您创建了一个多重选择(您应该使用ListBoxFor(),而不是DropDownListFor()),它发布一个值数组,因此它需要在方法中为string[] CountryId。并且不要为您绑定到的属性和SelectList 使用相同的名称
  • 能否请您为此提供一个 js 小提琴?我无法使它工作。你说的对我来说似乎是合乎逻辑的。所以我想看看一个可行的例子。
  • 因为它是一个数组,您还需要添加traditional: true, 选项, 将数据字符串化并使用contentType: 'json'
  • 感谢它现在的工作:)
  • 如果我将traditional: trueDropDownListFor() 一起使用,即使这样它也能正常工作。您能否将您的解决方案添加到答案部分,以便我接受?

标签: jquery ajax asp.net-mvc drop-down-menu multi-select


【解决方案1】:

您生成了一个&lt;select multiple="multiple"&gt;,它回发一组值,而不是单个值。

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

$.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' 选项并使用 JSON.stringify({ someProperty: yourComplexArray }); 对您的数据进行字符串化

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-25
    • 1970-01-01
    • 2013-09-14
    • 1970-01-01
    • 2017-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多