maximelian1986
maximelian1986

Reputation: 2452

Get data from ajax to mvc action

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

On back-end 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 front-end 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 like in example on top, container-object in action have Id value and have array of 2 elements in Filters, however both of them have Name and Values as null.

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

Any suggestion? Thank you.

Upvotes: 7

Views: 10297

Answers (3)

Subbu
Subbu

Reputation: 618

Though its an old post, adding my bit to it. I would ask if you are returning a view from the action or not? here it seems like you are not returning a view but just wanting to update some data.

But in case you wanted to return a view, for e.g like showing some product info, then you would just pass the selected product's id to the action method, retrieve the related product information and then pass on this data as a model to the view, and then return the complete view. In this case you don't need a separate ajax call to process the data, instead just do it when you are requesting for the view itself (through the action method).

On the contrary if you already have the view rendered and are just wanting to change the data inside the current view then just resort to an ajax call to get the data without any view.

Hope it helps

Upvotes: 0

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48337

Use a POST request in combination with JSON.stringify() method.

C#

[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 JSON.stringify() method ?

contentType is the type of data you're sending, so application/json; The default is application/x-www-form-urlencoded; charset=UTF-8.

If you use application/json, you have to use JSON.stringify() in order to send JSON object.

JSON.stringify() turns a javascript object to json text and stores it in a string.

Upvotes: 6

Amit Kumar
Amit Kumar

Reputation: 5962

You should use POST method instead of GET in ajax request. As you are posting data. and also your action should have [HttpPost] decorator.

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

Upvotes: 2

Related Questions