我试图将js ajax中的对象数组发布到asp.net mvc控制器。但控制器参数始终为空。是否有类型不匹配或其他什么?
Js ajax
var obj = {};
var arr = [];
obj = {
id: clicked.attr("name"),
name: clicked.text().trim()
}
if (clicked.hasClass("active")) {
clicked.removeClass("active");
clickedCount--;
arr.pop(obj);
}
else {
clicked.addClass("active");
clickedCount++;
arr.push(obj);
}
$.ajax({
url: "/Players/Shuffle",
type: "POST",
data: JSON.stringify({ list: arr }),
contentType: "json",
success: function (data) {}
});
控制器
[HttpPost]
public ActionResult Shuffle(List<player> list)
{
return RedirectToAction("Shuffled", new { l = list });
}
错误:控制器中的列表始终为空。
更新
除了上面的代码之外,为什么我看不到包含发布到Shuffle
的列表的新页面? Shuffled
应该处理这个问题。
public ActionResult Shuffled(List<Player> list)
{
ViewData["PlayerList"] = list;
return View(list);
}
CSHTML
@model List<Player>
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
@{
ViewBag.Title = "Shuffled";
}
<h1 id="test">
list: @ViewData["PlayerList"]
</h1>
答案 0 :(得分:1)
像这样更改你的代码,我认为它会起作用:
Js ajax
$.ajax({
url: "/Players/Shuffle",
type: "POST",
data: {list: JSON.stringify(arr)},
datatype: "json",
success: function (data) {}
});
<强>控制器强>
[HttpPost]
public ActionResult Shuffle(string list)
{
var js = new JavaScriptSerializer();
var deserializedList = (object[])js.DeserializeObject(list);
return RedirectToAction("Shuffled", new { l = deserializedList });
}