将二维数组作为json对象返回并迭代它

时间:2012-03-12 14:43:01

标签: json asp.net-mvc-3 jquery

我从我的mvc动作返回一个二维数组到我的视图,我想在对象上使用$ .each()函数来迭代它。出于某种原因,我无法让它发挥作用。

我的行动:

   [HttpPost]
    public JsonResult ShowTiles(TileModel tile)
    {

        MapModel map = HomeController.mapModel;
        map.MapTilesArray[tile.OldX, tile.OldY].Value = 4;

        var player = map.MapTilesArray[tile.OldX, tile.OldY].Player; 
        map.MapTilesArray[tile.X, tile.Y].Player = player;
        player.Position = new Point(tile.X,tile.Y);

        map.MapTilesArray[tile.X, tile.Y].Value = 2;

        return Json(map.MapTilesArray);
    }

我的模特:

    public MapModel()
    {

        MapTilesArray = new TileModel[10,10];

        for (int i = 0; i < 10; i++)
        {
            for (int j = 0; j < 10; j++)
            {
                MapTilesArray[i, j] = new TileModel();
                MapTilesArray[i, j].Value = 1;

            }
        }

        userNameList = new List<string>();
    }

我的观点:

   $.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(), 
                $.each(data, function (index, item) {
                    if (item.Value === 0) {
                        $("#" + item.Y + item.X).css("background-color", "brown");
                    }
                    else if (item.Value === 1) {
                        $("#" + item.Y + item.X).css("background-color", "black");
                    }
                    else if (item.Value === 2) {
                        $("#" + item.Y + item.X).css("background-color", "green");
                    }
                    else if (item.Value === 3) {
                        $("#" + item.Y + item.X).css("background-color", "blue");

                    }
                     else if (item.Value === 4) {
                        $("#" + item.Y + item.X).css("background-color", "purple");

                    }

                }), MovePlayer(newPosition.left + 15, newPosition.top + 15)
            },
            error: function () { showErrorMsg(); }
        });
    });

1 个答案:

答案 0 :(得分:0)

试试这个

你控制器中的

回显数组

$data = array(
   array(
      'title' => 'My title' ,
      'name' => 'My Name' ,
      'date' => 'My date'
   ),
   array(
      'title' => 'Another title' ,
      'name' => 'Another Name' ,
      'date' => 'Another date'
   )
);

echo json_encode($data);

然后你可以在你的视图中得到它并像这样迭代

var data = $.parseJSON(data);


for(x in data)
{
   alert(data[x]['title]);
   alert(data[x]['name]);
   alert(data[x]['date]);
}

尝试理解并适用于您的Senario