Passing Javascript Array to ASP.NET MVC Controller

I have the following javascript class that I am trying to pass to ASP.NET MVC Controller

 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";

This is how I call the Controller method:

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

On the controller side, I declared ViewModel as follows:

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

The My Controller Save method is declared as follows:

 public JsonResult Save(AttributeViewModel[] attributes)

When I execute, the value of the attributes is always zero.

Any ideas? Not sure how to start this debugging.

+5
source share
2 answers

You can try json.net to solve your problem

  [JsonFilter(Param = "attributes", JsonDataType = typeof(AttributeViewModel[]))]
  public JsonResult Save(AttributeViewModel[] attributes)

At the client:

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

        }
    });
+6
source

It looks like you need to add traditional : trueajax to the call. Look here and here.

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

All Articles