gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 13:31:23 25 4
gpt4 key购买 nike

假设我有一个像这样的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com