2012-02-29 11 views
0

私は次のモデルを持っています:private int [、] mapTilesArray = new int [10、10]; 私がしたいことは、$ .ajaxを使ってこのモデルを変更し、それをコントローラ から私のビューに戻すことです。次に、この配列内の値に基づいて、同様の配列のdivを作成したいと考えています。だから私はjson形式を使ってこのモデルを私のビューに戻す方法を知りません。戻り値Asp.Net MVC 3のコントローラから表示するための2次元配列配列

私の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()); 
    } 

は、どのようにこれが最も効率的な方法を行うことでしょうか?私の見解では、この配列をどのように再現できますか?

+0

、あなただけの "JSON(マップ)" を返す試してみましたか? – Dave

+0

いいえ、私はそうするでしょう –

+0

でも、どうすればその中の値をチェックできますか? –

答えて

0

本当の迅速かつ汚いソリューションは、以下の可能性があり、あなたは少しあちこちでそれを微調整する必要がある場合があります。)

のidので、私は、あなたがすでにあなたのページ上のセルを表す225件のdivのように持っていると仮定しています例えば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); 
}