我有一个 Controller 需要 List<int>
我正在从 AJAX 调用。 Controller 被击中,但参数始终是null
.
我的 Controller :
public ActionResult MinorAreas(List<int> majorareas)
{
// ...
}
jQuery 调用:
function onChange(e)
{
var cur = this.value(); // an array of numbers like [2,4,7,9]
$.ajax({
cache: false,
type: "GET",
traditional: true,
url: "@(Url.RouteUrl("GetMinorAreas"))",
data: { "majorareas": cur},
success: function (data) {...},
error: function (xhr, ajaxOptions, thrownError) {... }
});
}
路线定义:
routes.MapLocalizedRoute(
"GetMinorAreas",
"minorAreas",
new { controller="ProSearch", action="MinorAreas", majorareas=new List<int>() },
new[] { "ABC.ZZZ.Controllers" }
);
使用 fiddler,我可以看到 URI 构建正确:
# With an array of [2]
http://localhost:15536/minorAreas?majorareas=2&_=1450307693166
# With an array of [2,3,9]
http://localhost:15536/minorAreas?majorareas=2&majorareas=3&majorareas=9&_=1450308261808
我已经看过 this question关于将数组传递给带有 List<int>
的 Controller 参数,但解决方案似乎对我不起作用。我做错了什么?
最佳答案
看起来网络请求正在正确生成。问题出在路由定义中:
routes.MapLocalizedRoute(
"GetMinorAreas",
"minorAreas",
new { controller="ProSearch", action="MinorAreas", majorareas=new List<int>() },
new[] { "ABC.ZZZ.Controllers" }
);
majorareas=new List<int>()
将确保 majorareas
始终是一个空列表,即使它本来会被填充也是如此!
你不必在这里定义参数; Controller 中的方法定义 就是这样做的。将其关闭,它应该可以正常工作:
routes.MapLocalizedRoute(
"GetMinorAreas",
"minorAreas",
new { controller="ProSearch", action="MinorAreas" },
new[] { "ABC.ZZZ.Controllers" }
);
关于javascript - 使用 List<int> 参数将 javascript 数组传递给 Controller 的正确技术,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34322583/