我有一个模型,它是:private int[,]mapTilesArray=new int[10,10];我想做的是使用$.ajax修改这个模型,然后从控制器返回它在我看来。然后,基于这个数组中的任何值,我想在我的视图中构造一个类似的div数组。所以现在我不知道如何使用json格式将这个模型返回到我的视图中。
我的Ajax请求:
var backgroundColor;
$(function () {
$(".mapTile").click(function () {
$("#info").text($(this).attr("x"));
var tile = {
X: $(this).attr("x"),
Y: $(this).attr("y")
};
$.ajax({
beforeSend: function () { ShowAjaxLoader(); },
url: "/Game/ShowTiles",
type: "POST",
contentType: "application/json;charset=utf-8",
dataType: "json",
data: JSON.stringify(tile),
success: function (data) { HideAjaxLoader(); },
error: function () { HideAjaxLoader(); }
});
});
控制器:
[HttpPost]
public ActionResult ShowTiles(TileModel tile)
{
MapModel map = new MapModel();
map.MapTilesArray[tile.X, tile.Y] = 1;
return this.Content(map.MapTilesArray.ToString());
}
那么,如何才能以最有效的方式做到这一点呢?如何在视图中重新创建此阵列?
一个真正快速而肮脏的解决方案可能如下,您可能需要在这里或那里进行一些调整;)
我假设您的页面上已经有225个div代表单元格,id从例如cell_1到cell_225。
视图:
$.ajax({
beforeSend: function () { ShowAjaxLoader(); },
url: "/Game/ShowTiles",
type: "POST",
contentType: "application/json;charset=utf-8",
dataType: "json",
data: JSON.stringify(tile),
success: function (data) {
$.each(data, function (index, item) {
if (item) {
var cellnumber = ((item.Y * 15) + item.X);
$("#cell_" + cellnumber).innerText = item.Value;
}
});
HideAjaxLoader();
},
error: function () {
HideAjaxLoader();
}
});
控制器/型号:
public class MapModel
{
public TileModel[,] MapTilesArray;
public MapModel()
{
MapTilesArray = new TileModel[15, 15];
}
}
public class TileModel
{
public int X;
public int Y;
public int Value { get; set; }
}
[HttpPost]
public ActionResult ShowTiles(TileModel tile)
{
MapModel map = new MapModel();
map.MapTilesArray[tile.X, tile.Y] = new TileModel { X = tile.X, Y=tile.Y, Value = 1};
return Json(map.MapTilesArray);
}