Tânia B. Nielsen
Tânia B. Nielsen

Reputation: 31

Ajax Json passes the right data, but method gets object with null properties

I have an Ajax call that sends a list of objects to a method within the controller.
I looked at the json it sends and all seems to be in order. But when it gets to the controller, the list is there, with the right number of objects, but all of their properties are null, even though the values are correctly set at the json.

Example: I have a List with 10 objects in it, all of them with their properties set with specific values. I execute the call, but when the list gets to the controller it has 10 objects will all of their properties set as null.

Does someone knows why this happens?

Here is the call:
I had to use post instead of get because of the large amount of data.

$("#testeFA").click(function()
{
    <% JavaScriptSerializer serializador = new JavaScriptSerializer(); %>

    var models = <%: MvcHtmlString.Create(serializador.Serialize(apontamentos)) %>
    //"apontamentos" is the name of the List<ApontamentoModel>

    $.post('<%: Url.Action("GeraFA") %>', { models: models }, function (sucesso)
    {
        //do whatever
    }, 'json');
});

Here is the method:

public JsonResult GeraFA(List<ApontamentoModel> models) <- this is where the list shows all the objects' properties as null
{
    JsonResult result = new JsonResult();

    //do whatever

    result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
    return result;
 }

And here's a part of the json, so you can see the structure:

[{"DocEntry":1,
  "LineID":5,
  "Data":"01/06/2012",
  "HoraInicial":
      {"Ticks":288000000000,
       "Days":0,
       "Hours":8,
       "Milliseconds":0,
       "Minutes":0,
       "Seconds":0,
       "TotalDays":0.33333333333333331,
       "TotalHours":8,
       "TotalMilliseconds":28800000,
       "TotalMinutes":480,
       "TotalSeconds":28800},
  "CodigoCliente":"C00013",
  "Cliente":"Client Name",
  "CodigoProjeto":283,
  "Projeto":"Project Name",
  "CodigoServico":18,
  "TipoServico":"",
  "CodigoDespesa":0,
  "Despesa":"",
  "Quantidade":0,
  "NumeroChamado":0,
  "NumeroFA":10,
  "Apropria":true,
  "Narrativa":"teste",
  "NomeConsultor":"Name"},
 {"DocEntry":1,
  "LineID":13 //and so on to all the other elements

I'm using MVC2

Upvotes: 1

Views: 800

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

ASP.NET MVC 2 doesn't support JSON requests out of the box. This functionality has been built-in ASP.NET MVC 3. You could though write a custom JsonValueProviderFactory to achieve that. Phil Haack wrote an excellent blog post on this topic. You also need to use $.ajax instead of $.post as illustrated by Phil in order to be able to set the application/json request Content-Type header.

So once you download and register the JsonValueProviderFactory in your application you could:

$('#testeFA').click(function() {
    <% JavaScriptSerializer serializador = new JavaScriptSerializer(); %>
    //"apontamentos" is the name of the List<ApontamentoModel>
    var models = <%= serializador.Serialize(apontamentos) %>;
    $.ajax({
        url: '<%= Url.Action("GeraFA") %>',
        type: 'post',
        contentType: 'application/json;charset=utf-8',
        data: JSON.stringify({ models: models }),
        success: function(result) {
            //do whatever
        }
    });
});

Also notice the usage of the JSON.stringify method which converts the javascript models variable into a JSON string to be sent to the server as specified by the contentType parameter. This method is natively built-in all modern browsers. If you need to support some legacy browsers you could include the json2.js script to your page.

Upvotes: 1

Related Questions