post json string to mvc action via ajax comes null

1.3k Views Asked by At

I am posting a json object via ajax

    $('#btnOrder').click(function (e) {
        var jsonData = 
    {
        ScheduleDate: '20/07/2015 17:00',
        UnitNumber: '425196',
        Length: 0.00
    }

        var url = "http://mywebsite.com/Home/MakeOrder";
        $.ajax({
            type: "POST",
            dataType: "json",
            url: url,
            data: JSON.stringify(jsonData),
            contentType: "application/json",
            success: function(result) {

            }
        });
    });

to the following action:

[HttpPost]
public PartialViewResult MakeOrder(string jsonData)
{
    // some actions

    return this.PartialView("_Summary", summaryModel);
}

Model:

public class OrderItem
 {
        public DateTime? ScheduleDate {get;set;}
        public string UnitNumber {get;set;}
        public float Length {get;set;}
    }

The jsonData parameter value always comes null.

When I turn it into get ajax call via

var url = "http://mywebsite.com/Home/MakeOrder/?jsonData=" + jsonData

then the parameter comes fine as json string.

I need to send it via post.

EDIT ***** JS values

I'm debugging in Chrome and jsonData passed to 'ajax data:' is

JSON.stringify(jsonData)

gives

jsonData={"ScheduleDateTime":"20/07/2015 17:00","UnitNumber":"425196","Length":0.00}

if passed non stringified is:

jsonData = Object {"ScheduleDateTime":"20/07/2015 17:00","UnitNumber":"425196","Length":0.00}
1

There are 1 best solutions below

3
On

Similar SO question that will solve your issue

You will need to probably create an model to accept a list of instead of a list of strings.

public class MyJSONObject{

    public DateTime ScheduleDate { get; set; }

    public string UnitNumber { get; set; }

    public double Length { get; set; }

}

And accept it in your controller like:

[HttpPost]
public PartialViewResult MakeOrder(List<MyJSONObject> jsonData)
{
    // some actions
    return PartialView("_Summary", summaryModel);
}

And if it's not a list you need then just send off the single object and accept it in your controller as MyJSONObject jsonData instead.