MVC 2 - JavaScript数组到控制器不起作用

时间:2016-07-22 11:41:42

标签: jquery asp.net-mvc asp.net-mvc-2

我正在使用MVC2和.net framework 3.5

尝试将单个对象传递给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 个答案:

答案 0 :(得分: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);
}