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

Lan*_*nce 5 javascript asp.net-mvc

我有以下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";
Run Code Online (Sandbox Code Playgroud)

以下是我调用Controller方法的方法:

  var actionURL = "@Url.Action("Save", "Catalog")";
  $.ajax({
                    type: "POST",
                    url: actionURL,
                    data:  postParams   ......
Run Code Online (Sandbox Code Playgroud)

在Controller方面,我已经声明了一个ViewModel,如下所示:

 public class AttributeViewModel
 {
    public string name { get; set; }
    public string description { get; set; }
    public string attributeType { get; set; }
    public string value { get; set; } 
 }
Run Code Online (Sandbox Code Playgroud)

我的Controller Save方法声明如下:

 public JsonResult Save(AttributeViewModel[] attributes)
Run Code Online (Sandbox Code Playgroud)

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

有任何想法吗?不知道如何开始调试这个.

San*_*huk 6

您可以尝试使用json.net库来解决您的问题

  [JsonFilter(Param = "attributes", JsonDataType = typeof(AttributeViewModel[]))]
  public JsonResult Save(AttributeViewModel[] attributes)
Run Code Online (Sandbox Code Playgroud)

在客户:

$.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) {

        }
    });
Run Code Online (Sandbox Code Playgroud)