Erick Asto Oblitas
Erick Asto Oblitas

Reputation: 1409

Post json object to ASP MVC doesn't work properly

I'm trying to post a custom Json object to ASP.NET MVC controller, but doesn't work properly.

My JS Code is:

var myData = {
    "Message": "Another message",
    "Value": 4,
    "FirstItem": {
        "ItemName": "Este es el primer Item"
    },
    "SecondItem": {
        "ItemName": "Este es el segundo Item"
    }
};

$('.clickeable').click(function () {
    $.ajax({
        type: 'POST',
        dataType: 'json',
        data: myData,
        url: '@Url.Action("PostSomething")',
        success: function () {
            console.info('Success');
        },
        error: function () {
            console.info('Error');
        }
    });
});

In my Controller:

[HttpPost]
public JsonResult PostSomething(SimpleModel model)
{
    return Json(true);
}

public class SimpleModel
{
    public string Message { get; set; }
    public int Value { get; set; }
    public SimpleItem FirstItem { get; set; }
    public SimpleItem SecondItem { get; set; }
}

public class SimpleItem
{
    public string ItemName { get; set; }
    //more depth,
}

When get the HttpPost the properties FirstItem and SecondItem always been null. Posting JsonObject

Thanks in advance.

Upvotes: 0

Views: 1611

Answers (3)

Sajeev
Sajeev

Reputation: 197

I have tried your scenario.I found out solution that

var myData = {
    "Message": "Another message",
    "Value": 4,
    "FirstItem": {
        "ItemName": "Este es el primer Item"
    },
    "SecondItem": {
        "ItemName": "Este es el segundo Item"
    }
};

    var obj = { 'model': myData };
    var val=JSON.stringify(obj);

$('.clickeable').click(function () {
    $.ajax({
        type: 'POST',
        dataType: 'json',
        data: val,
        contentType:"application/json",
        url: '@Url.Action("PostSomething")',
        success: function () {
            console.info('Success');
        },
        error: function () {
            console.info('Error');
        }
    });
});

in your code you are not specifying the content type.Just try this

Upvotes: 4

fyjham
fyjham

Reputation: 7034

It's because of how jQuery translates your JSON object into POST parameters messes up C#'s ability to read it (jQuery tries to map the properties of the javascript object to variables on the post, MVC is smart enough though to just have raw JSON posted a it).

The simplest solution is just to stringify it first and it should deserialize properly (data: JSON.stringify(myData)).

Note that if you're supporting old browsers you'll need to add the json2.js library for that function, but it's built in in all modern browsers.

Upvotes: 1

Nikitesh
Nikitesh

Reputation: 1305

Not a proper solution but try:

[HttpPost]
public JsonResult PostSomething(string Message, int Value,SimpleItem FirstItem,SimpleItem  SecondItem )
{
    return Json(true);
}

Upvotes: 1

Related Questions