问题描述
假设我有一个像这样的ViewModel:
Let's say I have a ViewModel like this:
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; }
}
和这样的控制器:
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请求变为:
The problem is when I try to trigger the validation, the actual HTTP GET request becomes:
http://localhost:8080/Baz/CheckIds?id=4&barIds=7%2C8 /* <-- barIds=7,8 */
而不是:
http://localhost:8080/Baz/CheckIds?id=4&barIds=7&barIds=8
默认模型绑定器无法将 int
绑定到 IEnumerable< int>
。我该如何解决?
which the default model binder failed to bind the int
s to IEnumerable<int>
. How can I fix that?
推荐答案
jquery.validate和jquery.validate.unobstrusive不处理数组。
如果你真的需要处理数组,你需要修改它们。
jquery.validate and jquery.validate.unobstrusive doesn't handle arrays.If you really need to handle arrays, you need to modify them.
我能想到的最短解决方案:
Shortest solution I can think of:
1)在的
进入此远程
函数中修改 $。ajax
调用jquery.validate
1) Modify the $.ajax
call at the remote
function of jquery.validate
into this
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)将 traditional:true
添加到远程
的适配器jquery.validate.unobstrusive
var value = {
url: options.params.url,
type: options.params.type || "GET",
data: {},
traditional: true //so that MVC is able to de-serialize arrays
}
这篇关于RemoteAttribute未将查询字符串作为IEnumerable传递< T>正确地的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!