小编典典

传递给MVC Action的JSON Date参数始终为null

json

我有一系列通过jQuery Ajax传递给MVC JsonResult操作的参数。在大多数情况下,它们成功到达,但是有一个Date值根本没有到达。

为了使此日期成功到达,我需要使用什么考虑因素/格式?或者我需要采取什么方法?

...other code ...
myStory.Deadline = new Date($('#story-deadline').val());

$.ajax({
    url: '/Project/' + action[2] + '/AddStory',
    data: { Summary: myStory.Summary, Size: myStory.Size, Priority: myStory.Priority,
            Owner: myStory.Owner, Deadline: myStory.Deadline },
    dataType: 'json',
    traditional: true,
    type: 'POST',
...the rest of the code...

JsonResult操作:

[HttpPost]
public JsonResult AddStory(int projectid, Story story)
{
...some code that doesn't have a DateTime object to work with...

阅读 272

收藏
2020-07-27

共1个答案

小编典典

Microsoft使用JavaScriptSerializer对ASP.NET
MVC数据进行序列化/反序列化。如果使用/Date(utcDate)/格式作为Date数据类型。尝试使用

'"\\/Date(' + myStory.Deadline.getTime() + ')\\/"'

要么

var d = myStory.Deadline;
var dateForMS = '"\\/Date(' +
        Date.UTC (d.getUTCFullYear(), d.getUTCMonth(),
                  d.getUTCDate(), d.getUTCHours(),
                  d.getUTCMinutes(), d.getUTCSeconds(),
                  d.getUTCMilliseconds()) + ')\\/"'

您也可以只使用Sys.Serialization.JavaScriptSerializerfrom
MicrosoftAjax.js进行序列化Deadline或任何其他Date类型。

更新 :也许你应该用'\/Date('')\/'代替'"\\/Date('')\\/"'。一切取决于您将在何处插入字符串。

更新2 :现在我拥有了!ASP.NET
MVC主要用于每个Ajax的发布表单字段。在服务器端,将仅使用Parse每种类型的方法将发布的参数转换为该类型。因此,可以使用DateTime.Parse支持的任何字符串格式。例如,您可以使用ISO 8601格式,例如“
2010-08-29T13:15:00.0000000Z”。为此,可以在现代浏览器(firefox,chrome)中使用toISOString()功能。为了更加独立,可以实现数据转换,如http://williamsportwebdeveloper.com/cgi/wp/?p=503中所述

var d = new Date($('#story-deadline').val())
//var d = new Date(); // get the date. Here we use just Now.
var dAsISOString;
if ($.isFunction(d.toISOString)) {
    //alert("internal toISOString are used!");
    dAsISOString = d.toISOString();
}
else {
    dAsISOString = d.getUTCFullYear() + '-' + padzero(d.getUTCMonth() + 1) + '-' +
                   padzero(d.getUTCDate()) + 'T' + padzero(d.getUTCHours()) + ':' +
                   padzero(d.getUTCMinutes()) + ':' + padzero(d.getUTCSeconds())+'.'+
                   pad2zeros(d.getUTCMilliseconds()) + 'Z';
}
var myStory = { Summary: 'Test description', Size: 8, Dedline: dAsISOString };
$.ajax({
    url: '/Project/1/AddStory',
    data: { Summary: myStory.Summary, Size: myStory.Size, Dedline: myStory.Dedline },
    dataType: 'json',
    // ...
});
2020-07-27