Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 3 AJAX Post, List filled with Objects, but Objects Properties are Empty

I have the following problem:

On a Button-Click I POST some data to the server. My controller Action looks like this:

public ActionResult Accept(List<MyViewModel> entries)
{
    //here entries HAS 2 MyViewModel-Instances in it.
    //The entries are not null, but the values of the instances are!
    //entries[0].ParamA is null
}

Where the MyViewModel looks like this:

public class MyViewModel
{
    public string ParamA { get; set; }
    public string ParamB { get; set; }
}

And the AJAX-Call is the follwing:

var myEntries = { entries: [{ ParamA: "A", ParamB: "B" }, { ParamA: "C", ParamB: "D" }] };

$.ajax({
    type: 'POST',
    url: url,
    cache: false,
    data: myEntries,
    dataType: 'text' });

What i already tried to do:

  • Changed dataType to 'json'
  • used: traditional: true
  • tried var myEntries = JSON.stringify(...);
  • tried var myEntries = { entries : [JSON.stringify({ ... }), JSON.stringify({ ... })] };
  • same as above, but with jQuery.param(..., true);
  • Use of IEnumerable or MyViewModel[] instead of list.
  • ANY combination of the above

What am I doing wrong here?

Thank you very, very much in advance for helping me!

EDIT

My (Razor)View is not interesting at this moment as it has nothing to do with anything. I am NOT using any of the HTML.TextBoxFor (or similiar) Methods to fill the myEntries-Variable. It is actually filled dynamically (because there are many many conditions). For the sake of the question (and my own testing) i hard-coded the variable. :)

like image 269
Shion Avatar asked Apr 11 '12 07:04

Shion


Video Answer


3 Answers

With your answer and the use of JSON.stringify method it works for me

var myEntries = { entries: [{ ParamA: "A", ParamB: "B" }, 
                            { ParamA: "C", ParamB: "D" }] };

$.ajax({
        type: 'POST',
        url: '/{controller}/{action}',
        cache: false,
        data: JSON.stringify(myEntries),
        dataType: 'json', 
        contentType: 'application/json; charset=utf-8'
    });
like image 122
Andrew Avatar answered Sep 30 '22 06:09

Andrew


I got the answer!

jQuery can be confusing at times.

dataType is the parameter which specifies what you want to get BACK from the server. contentType is the paremeter which specifies what you SEND TO the server.

So from the example above it works if you add:

contentType: 'application/json; charset=utf-8',

in the AJAX-call.

like image 33
Shion Avatar answered Sep 30 '22 05:09

Shion


Just to compliment the answer on how to create the list that will be post back to the controller. That is because you don't need to wrap the array with the name of the list. It looks ugly and is not manageable using built in functions. This example is here to show how to post back JSON that MVC will understand and interpret as a List of. (But even if the Array is wrapped it still works but that is static content and difficult to manage)

This example used jQuery's sortable plugin. I want to post the entire list model back with the new ordering indexes to save in the database.

update: function (event, ui) {

 img = { key: 0, order: 0, url: '' }; //Single image model on server
 imgs = new Array(); //An array to hold the image models.

 //Iterate through all the List Items and build my model based on the data.
 $('#UploaderThumbnails li').each(function (e) {
      img.key = $(this).data('key');  //Primary Key
      img.order = $(this).index();  //Order index
      imgs.push(img); //put into "list" array
 });

 //And what is in the answer - this works really great
 $.ajax({
     url: '/Image/UpdateOrder',
     data: JSON.stringify(imgs),
     type: 'POST',
     contentType: 'application/json; charset=utf-8'
  });

}

And my MVC controller is as simple as ...

  [HttpPost]
  public ActionResult UpdateOrder(List<Models.Image> images)
  {
     //Images at this point is a proper C# List of Images! :) Easy!

      return Content("");
  }
like image 20
Piotr Kula Avatar answered Sep 30 '22 07:09

Piotr Kula