简体   繁体   中英

AJAX sends date in data but C# controller does not contain data

I came accross weird behaviour in my MVC site sending ajax request. I have following call in one of funcitons:

$.ajax ({
    data: JSON.stringify({event_id: params.eventId, start_date: params.startDate}),
    type: "POST",
    async: false,
    contentType: "application/json; charset=utf-8",
    url: '@Url.Action("RandomFunction")',
    success: function(return string) {
        //DoSomeStuff
    }
});

Then there is this function in controller:

[HttpPost]
public ActionResult RandomFunction(int eventId = 1, string startDate = "")
{
    if (startDate == string.Empty) {
        //Handle missing date
    }

    //DoSomeMagic
}

Google Chrome's Developer tool shows that required data were sent via post request.

Request Payload:
event_id: "1"
start_date: "2015-06-08T22:00:00.000Z"

But once it reaches RandomFunction, startDate string is set to empty string instead of date that was sent via request and code ends up in Handle missing date section

Am I doing something wrong? I can't figure it out for a while.

This example works for me:

$.ajax ({
    data: {
        eventId: params.eventId, 
        startDate: params.startDate
    },
    type: "POST",
    async: false,
    contentType: "application/json; charset=utf-8",
    url: '@Url.Action("RandomFunction")',
    success: function(return string) {
        //DoSomeStuff
    }
});

And C# code:

[HttpPost]
public ActionResult RandomFunction(int eventId, string startDate)
{
    if (startDate == string.Empty) {
        //Handle missing date
    }

    //DoSomeMagic
}

Try This, Your passing parameter name and Receiving Para Name in controller are different so.. make them same..

[HttpPost]
public ActionResult RandomFunction(int event_id= 1, string start_date= "")
{
    if (start_date== string.Empty) {
        //Handle missing date
    }

    //DoSomeMagic
}

Regards,

I would expect your problem is due to the use of JSON.stringify there is a difference between

"{event_id: 1, start_date: \"2015-06-08T22:00:00.000Z\"}"

which is just a string, and

{event_id: 1, start_date: "2015-06-08T22:00:00.000Z"}

which is a JObject that the MVC framework can parse.

Also make sure that the names in the JSON match the names of the arguments

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