I'm trying to post an array of objects from js ajax to asp.net mvc controller. But controller parameter is always comes null. Is there a type mismatch or something else?
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) {}
});
Controller
[HttpPost]
public ActionResult Shuffle(List<player> list)
{
return RedirectToAction("Shuffled", new { l = list });
}
Error: list in controller is always null.
UPDATE:
In addition to the code above, why can't I see a new page with the list that posted to the Shuffle
? Shuffled
should be dealing with this.
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 }),
and addcontentType: 'json'
and change your parameter toList<T>
whereT
is a model containing propertiesid
andname
(but since your array only contains one object, why post an array?)data: { [0].id: x, [0].name: y, [1].id: xx, [1].name: yy ..... }
null
if you use the code in my initial comment.