I am using ASP.NET MVC 4 and I am trying to send a JSON object to a controller that accepts

Here is my javascript and jQuery:

var jsonObject = {
    "PlantShipTo":{
        "PlantID" : shipToID.toString()
    }
};

$.ajax({
    type: "POST",
    contentType: 'application/json; charset=utf-8',
    timeout: 15000,
    url: "/Transfer/TransferOut",
    data: JSON.stringify(jsonObject),
    dataType: 'json',
    tradational: 'true',
    success: function (response) {
    }
});

In my controller I am accepting an object of type "PlantShipTo" defined below:

public class PlantShipTo
{
    public int PlantID { get; set; }
}

For brevity, I will only show the controller definition:

public ActionResult TransferOut(PlantShipTo shipto)
{
    PlantShipTo p = shipto;

I expect the MVC model binding to recognize the JSON as a PlantShipTo object, but the object is null when I check it in the controller. Below is some of my request info courtesy of Fiddler. The JSON looks like it matches my "PlantShipTo" class. What am I missing ?

Accept: application/json, text/javascript, */*; q=0.01
Content-Type: application/json; charset=utf-8
X-Requested-With: XMLHttpRequest
{"PlantShipTo":{"PlantID":"2"}}
有帮助吗?

解决方案

MVC can automatically model bind only if the data you send matches the name of the parameter specified in your controller.

You can change the name of the root element in your JSON to match your parameter name:

var jsonObject = {
    "shipTo":{
        "PlantID" : shipToID.toString()
    }
};

Or remove the root element so MVC can automatically bind to the parameter's properties:

var jsonObject = {
    "PlantID" : shipToID.toString()
};

其他提示

You JSON Object is not so right. Check the correct one -

        var jsonObject = {
                "PlantID": YourVariable
        };

        $.ajax({
            url: "@Url.Action("TransferOut")",
            type: "POST",
            data: JSON.stringify(jsonObject),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            error: function (response) {
                alert(response.responseText);
        },
            success: function (response) {
                alert(response);
            }
        });

Output -

enter image description here

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top