2016-07-22 67 views
0

我在MVC2工作和.NET Framework 3.5MVC 2 - JavaScript的數組控制器不工作

雖然試圖通過一個單一的對象MVC控制器這是工作的罰款。但是當我嘗試將值作爲數組傳遞時,我在控制器中將屬性值設置爲null。

我正在使用下面的代碼來執行此操作。

的JavaScript

var tdmsConfiguredLayersList = [{Id:1,Name:'Test1'},{Id:2,Name:'Test2'}]; 
    $.ajax({ 
      type: "POST", 
      //contentType: 'application/json; charset=utf-8', 
      //JSON.stringify({ layers: tdmsConfiguredLayersList }), 
      data:{layers:tdmsConfiguredLayersList}, 
      url: rootUrl + "Map/CatalogueDrawing", 
      dataType: "json", 
      success: function (result) { 
       debugger; 
      }, 
      error: function (errResult) { 
       debugger; 
      } 

    }); 

控制器代碼

[HttpPost] 
public void CatalogueDrawing(List<LayerViewModel> layers) 
{ 

} 

Result that is returned

LayerViewModel類

public class LayerViewModel 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
} 
+1

反序列化你的commened代碼是幾乎沒有。你需要添加'contentType:'application/json; charset = utf-8','並使用'data:JSON.stringify({layers:tdmsConfiguredLayersList})' –

+0

我也試過。但它不起作用 –

+0

它確實工作:)(並假設它的'MapController',然後使用'url:'@ Url.Action(「CatalogueDrawing」,「Map」)',' - 不要硬編碼url的) –

回答

0

另一種方式來傳遞你的列表中的.NET 3.5控制器是將它們作爲JSON字符串,並從控制器

using System.Web.Script.Serialization; 



var tdmsConfiguredLayersList = [{Id:1,Name:'Test1'},{Id:2,Name:'Test2'}]; 
    tdmsConfiguredLayersList = JSON.stringify(tdmsConfiguredLayersList); 
    $.ajax({ 
      type: "POST", 
      data: { jsonString: tdmsConfiguredLayersList }, 
      url: rootUrl + "Map/CatalogueDrawing", 
      dataType: "json", 
      success: function (result) { 
       debugger; 
      }, 
      error: function (errResult) { 
       debugger; 
      } 

    }); 


public void CatalogueDrawing(string jsonString) 
{ 
     var jss = new JavaScriptSerializer(); 
     List<LayerViewModel> layers = jss.Deserialize<List<LayerViewModel>>(jsonString); 
}