c# - RemoteAttribute 没有将查询字符串作为 IEnumerable<T> 正确传递

标签 c# jquery asp.net-mvc-4

假设我有一个像这样的 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.validateremote函数处的$.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/

相关文章:

c# - 如何在 .NET 3.5 中通过 NamedPipe 发送对象?

c# - WebRequest.GetResponse() 在几次请求后超时

jquery - IE9 : Getting the value of 'MS Filter' property using jquery

razor - 如何使 MVC 4 Razor Html.Raw 在脚本标签内的 HTML 中赋值

c# - 如何在 asp.net mvc 中正确检测用户浏览器文化

javascript - 使用与 MVC PartialViewResult 签名匹配的对象动态填充 Ajax 数据属性

c# - 异步等待很少有混淆

c# - 使用安装项目将文件复制到远程服务器

javascript - 如何将选中的复选框数据附加到html <div> 标签中的列表顶部?

jquery - 如果按钮有类做某事,如果有不同的类做其他不工作jquery