2010-08-27 114 views
4

我有一系列通過jQuery Ajax傳遞給MVC JsonResult操作的參數。在大多數情況下,這些成功到達,但有一個日期值根本沒有到達。傳遞給MVC的JSON日期參數操作始終爲空

我需要使用哪些考慮因素/格式 - 或者需要採取哪些方法 - 才能使此日期成功到達?

...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... 

回答

5

微軟使用JavaScriptSerializer序列化/ desirealize的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.JavaScriptSerializerMicrosoftAjax.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', 
    // ... 
}); 
+0

我試過原有的格式建議和更新之一,雙方還沒有到齊爲空兩者。他們被正確發佈,但:截止日期\t「/ Date(1283169600000)/」 – 2010-08-27 12:00:19

+0

似乎應該用MVC的源代碼測試問題(請參閱http://weblogs.asp.net/jacqueseloff/archive/2010 /04/20/mvc-2-source-code-released-to-microsoft-reference-server.aspx和http://aspnet.codeplex.com/releases/view/41742)。如果你有任何結果,請告訴我。 – Oleg 2010-08-27 14:28:57

+0

它只適用於我手動序列化數據爲json的情況。 ** data:JSON.stringify(params),** – vsapiha 2012-02-20 14:07:21