简体   繁体   中英

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. 发布JsonObject

Thanks in advance.

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

Not a proper solution but try:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM