Get data from ajax to mvc action

I want to send an array of objects from an ajax call to a controller action.

On the server side, I have

container classes:

public class MyContainer
{
    public string Id { get; set; }
    public Filter[] Filters { get; set; }
}

public class Filter
{
    public string Name { get; set; }
    public string[] Values { get; set; }
}

and action:

public ActionResult MyAction(MyContainer container)
{
   var id = container.Id;
   foreach(Filter filter in container.Filters)
   {
       //Do something
   }
}

On the interface side, I have

$(document).on('click', 'mySelector', function (event) {

    //Create first object
    var firstIds = {};
    firstIds.Name = "Custom Name 1";
    firstIds.Values = GetIds('param1'); //this return an array of strings

    //Create second object
    var secondIds = {};
    secondIds.Name = "Custome Name 2";
    secondIds.Values = GetIds('param2'); //another array

    var Id = $(this).attr('id'); //id of element

    //Add objects to array
    var filters = [];
    filters.push(firstIds);
    filters.push(secondIds);

    $.ajax({
        method: "GET",
        url: baseUrl+"/MyAction",
        //traditional: true, //I tried with and without that parameter
        data:
        {
            Id: Id,
            Filters: filters
        },
        contentType: 'application/json',
        success: function (res) {
            alert('success')
        }
    });
});

So, if I use it, as in the example above, the container object in action has an Id value and has an array of 2 elements in Filters, however both of them have a name and values ​​as null.

With the traditional set True, I got container.Id installed, but container.Filters = null.

Any suggestion? Thank.

+4
source share
2 answers

Use the query POSTin conjunction with a method JSON.stringify().

WITH#

[HttpPost]
public ActionResult MyAction(MyContainer container)
{
   var id = container.Id;
   foreach(Filter filter in container.Filters)
   {
       //Do something
   }
}

JQuery

$.ajax({
    method: "POST",
    url: baseUrl+"/MyAction",
    data:JSON.stringify(
    {
        Id: Id,
        Filters: filters
    }),
    contentType: 'application/json',
    success: function (res) {
        alert('success')
    }
});

Why do you need a method JSON.stringify()?

contentType - , , application/json; application/x-www-form-urlencoded; charset=UTF-8.

application/json, JSON.stringify() JSON.

JSON.stringify() javascript json string.

+4

POST GET ajax. . [HttpPost].

$.ajax({
        method: "POST",
        url: baseUrl+"/MyAction",
        data:
        {
            Id: Id,
            Filters: filters
        },
        contentType: 'application/json',
        success: function (res) {
            alert('success')
        }
    });
+2

Source: https://habr.com/ru/post/1687415/


All Articles