【发布时间】: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: true与DropDownListFor()一起使用,即使这样它也能正常工作。您能否将您的解决方案添加到答案部分,以便我接受?
标签: jquery ajax asp.net-mvc drop-down-menu multi-select