【发布时间】:2016-05-31 11:38:44
【问题描述】:
我正在尝试将一组对象从 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>
【问题讨论】:
-
data: JSON.stringify({ list: arr }),并添加contentType: 'json'并将您的参数更改为List<T>其中T是包含属性id和name的模型(但由于您的数组仅包含一个对象,为什么要发布一个数组?) -
我必须用json传递吗?我不能按原样发送吗?
-
除非您使用索引属性名称 -
data: { [0].id: x, [0].name: y, [1].id: xx, [1].name: yy ..... } -
在调试中,我看到列表再次为空,但是当我运行它时,我在 firebug 中看到了正确的帖子值。(这是我不明白的情况)。无论如何,我现在要更新问题。
-
如果你使用我最初评论中的代码,它不会是
null。
标签: c# asp.net ajax asp.net-mvc