简体   繁体   English

AJAX在数据中发送日期,但C#控制器不包含数据

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

I came accross weird behaviour in my MVC site sending ajax request. 我在发送Ajax请求的MVC网站中遇到奇怪的行为。 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. Google Chrome的开发者工具显示所需数据是通过发布请求发送的。

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 但是一旦到达RandomFunction,startDate字符串将被设置为空字符串,而不是通过请求发送的日期,并且代码将在Handle missing date部分中结束

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: 和C#代码:

[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 我希望您的问题是由于使用JSON.stringify之间存在差异

"{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. 这是MVC框架可以解析的JObject。

Also make sure that the names in the JSON match the names of the arguments 还要确保JSON中的名称与参数名称匹配

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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