假设我有一个像这样的 ViewModel:
public class Foo
{
public int Id { get; set; }
public IEnumerable<SelectListItem> AvailableBars { get; set; } /* For populating DropDownList */
[Remote("CheckIds", "Baz", AdditionalFields = "Id")]
public IEnumerable<int> BarIds { get; set; }
}
还有这样的 Controller :
public class BazController
{
// ...CRUD operations skipped
public ActionResult CheckIds(int id, IEnumerable<int> barIds)
{
bool isValid = /* Logic for checking validity */
if (!isValid)
{
return Json("Error", JsonRequestBehavior.AllowGet);
}
return Json(true, JsonRequestBehavior.AllowGet);
}
}
在我看来:
@Html.DropDownListFor(model => model.BarIds, Model.AvailableBars, new { multiple = "multiple" })
问题是当我尝试触发验证时,实际的 HTTP GET 请求变为:
http://localhost:8080/Baz/CheckIds?id=4&barIds=7%2C8 /* <-- barIds=7,8 */
代替:
http://localhost:8080/Baz/CheckIds?id=4&barIds=7&barIds=8
默认模型绑定(bind)器无法绑定(bind) int
s 至 IEnumerable<int>
.我该如何解决?
最佳答案
jquery.validate 和 jquery.validate.unobstrusive 不处理数组。 如果你真的需要处理数组,你需要修改它们。
我能想到的最短的解决方案:
1) 将jquery.validate
的remote
函数处的$.ajax
调用修改成这样
var ajaxOptions = $.extend(true, {
url: param,
mode: "abort",
port: "validate" + element.name,
dataType: "json",
data: data,
success: function (response) {
...
}
}, param);
//Fix the bug
//we are not supposed to pass functions to data parameter
//capture the function output so array values are
//serialized properly
$.each(ajaxOptions.data, function (key, value) {
if ($.isFunction(value)) {
ajaxOptions.data[key] = value();
}
});
$.ajax(ajaxOptions);
2) 在jquery.validate.unobstrusive
remote
适配器中添加traditional: true
var value = {
url: options.params.url,
type: options.params.type || "GET",
data: {},
traditional: true //so that MVC is able to de-serialize arrays
}
关于c# - RemoteAttribute 没有将查询字符串作为 IEnumerable<T> 正确传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20415648/