将Javascript数组传递给ASP.NET MVC控制器

5

我有下面这个Javascript类,我想传递给一个ASP.NET MVC控制器。

 var postParams = {

         attributes : [
                         {
                            name : '',
                            description: '',
                            attributeType : '',
                            value : ''
                        }
                      ]
    };

 postParams.attributes[0] = new Object();
 postParams.attributes[0].name = "test";
 postParams.attributes[0].description = "test";
 postParams.attributes[0].attributeType = "test";
 postParams.attributes[0].value = "test";

这是我调用控制器方法的方式:
  var actionURL = "@Url.Action("Save", "Catalog")";
  $.ajax({
                    type: "POST",
                    url: actionURL,
                    data:  postParams   ......

在控制器侧,我声明了一个ViewModel如下:

 public class AttributeViewModel
 {
    public string name { get; set; }
    public string description { get; set; }
    public string attributeType { get; set; }
    public string value { get; set; } 
 }

我的控制器Save方法声明如下:

 public JsonResult Save(AttributeViewModel[] attributes)

当我执行时,属性值始终为null。

有什么想法吗?不确定如何开始调试。

2个回答

6
您可以尝试使用json.net库来解决您的问题。
  [JsonFilter(Param = "attributes", JsonDataType = typeof(AttributeViewModel[]))]
  public JsonResult Save(AttributeViewModel[] attributes)

在客户端:

$.ajax({
        type: 'POST',
        url: url,
        async: true,
        data:  JSON.stringify(attributes), //!!! Here must be the same name as in controller method
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        success: function (data) {

        },
        error: function (xhr, ajaxOptions, thrownError) {

        }
    });

感谢您的建议。已经添加了对Json.net的引用并添加了过滤器,但是null仍然传递给属性。 - Lance
你好,我遇到了同样的问题,我安装了json.net。你能帮我解决一下在哪里放置[JsonFilter(Param = "mydata", JsonDataType = typeof(AttributeViewModel[]))]吗? - touinta
我收到了这个错误:找不到类型或命名空间名称“JsonFilterAttribute” - touinta

1

看起来你需要在ajax调用中添加traditional : true。请查看这里这里

 $.ajax({ 
                traditional: true,
                type: "POST", 
                url: actionURL, 
                data:  postParams   

加上了 traditional: true 但是并没有解决问题。我已经花费太长时间在这个问题上了,所以现在会将一个逗号分隔的数组传递给控制器。 - Lance

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接