我一直在尝试使用AJAX将对象数组发送到控制器方法,但是即使尝试了各种方法,我仍然无法获得理想的结果。这是我当前的代码:
查看
function SaveGame() {
if ('@Session["Username"]' == '@Model.Player1.Username') {
p1 = true;
}
else {
p1 = false;
}
var characters = document.getElementsByClassName("char");
var chardata = [];
for (var i = 0; i < characters.length; i++) {
var id = characters[i].id;
var state = characters[i].classList[1];
chardata.push(id, state);
}
console.log(chardata);
$.ajax({
url: '@Url.Action("SaveGame", "Game")',
type: 'GET',
data: JSON.stringify({ 'character': chardata }),
cache: false,
contentType: 'application/JSON',
success: function (result) {
alert("Game Saved");
}
});
}
Gamecontroller / SaveGame
public bool SaveGame(JsonDecode character)
{
ViewGame game = (ViewGame)TempData["game"];
TempData["game"] = game;
return true;
//return charLayer.SaveCharacters(game.Id, ids, states, isPlayer1);
}
character
将为空
JsonDecode
public class JsonDecode
{
public object[] chardata { get; set; }
}
答案 0 :(得分:2)
您当前的代码使用GET
作为$ .ajax调用的类型。 jQuery ajax会向端点发出GET请求,并将数据附加到要进行调用的URL的查询字符串中。要发送简单值时可以,但是,当要发送复杂对象(如要发送的对象)时,则应使用POST类型。
此外,为了使模型绑定起作用,数据的结构应类似于您的视图模型结构和属性名称。根据您要发送的数据,看起来您需要这样的视图模型。
public class GameStateVm
{
public int Id { set;get;}
public string State { set;get;}
}
public class SaveGameVm
{
public GameStateVm[] Character { set;get;}
public bool PFlag { set;get;}
}
可用作您的HttpPost操作方法的参数。
[HttpPost]
public ActionResult SaveGame(SaveGameVm characters)
{
// I am simply returning the posted data as it is, for testing
// You may return a boolean value if you want that.
return Json(characters);
}
现在在您的客户端代码中,确保您的JS对象具有相似的结构和属性名称。
// JS object with same structure as our SaveGameVm
var d = { PFlag: false, character:[]};
d.PFlag = true; // to do : Set the value based on your condition
// dummy code to add 2 items to the array.
// to do : replace with your code to populate the array
for (var i = 0; i < 2; i++) {
var id =i; // to do : replace hard coded values
var state = 'active';
d.character.push({ id: id, state: state});
}
$.ajax({
url: '@Url.Action("SaveGame", "Game")',
type: 'POST',
data: JSON.stringify(d),
contentType: 'application/JSON',
success: function (result) {
console.log(result);
}
});