将日期值从Ajax调用传递给MVC

我的Ajax电话

$('#QuickReserve').click(function () { var now = new Date(); alert(now); var _data = { 'ComputerName': _computerName, '_mStart': now.toTimeString(), '_mEnd': now.toDateString() }; $.ajax({ cache: false, // contentType: "application/json; charset=utf-8", type: "POST", async: false, url: "/Home/SetMeeting", dataType: "json", data: _data, success: "", error: function (xhr) { alert("Error"); alert(xhr.responseText); } }); }); 

我的C#代码

  public ActionResult SetMeeting(string ComputerName, DateTime? _mStart, DateTime? _mEnd) { } 

代码结束时未收到DateTime值…..它们只显示为空白。 在jquery当我试图

 '_mStart': now.toTimeString(), '_mEnd': now.toDateString() 

到datetring确实返回今天的日期,但是,我也希望时间成为约会时间的一部分。

不要使用数据格式做任何技巧。 只需使用标准函数date.toISOString() ,它以ISO8601格式返回。

来自javascript

 $.post('/example/do', { date: date.toISOString() }, function (result) { console.log(result); }); 

来自c#

 [HttpPost] public JsonResult Do(DateTime date) { return Json(date.ToString()); } 

将json日期转换为此格式“mm / dd / yyyy HH:MM:ss”是整个​​技巧dateFormat是jsondate format.js文件中的函数,可在http://blog.stevenlevithan.com/archives/date-time找到-格式

 var _meetStartTime = dateFormat(now, "mm/dd/yyyy HH:MM:ss"); 

你能不能只传递一个DateTime,并将Date部分与服务器上的时间部分分开?

你能不能只通过’_mDate’:现在;

 public ActionResult SetMeeting(string ComputerName, DateTime? _mDate) { // Then in here use _mDate.Date, and _mDate.Time } 

为什么不将日期(和时间)转换为Unix Epoch的时间戳,然后使用js显示日期?

C#

 public double FromUnixEpoch(DateTime value) { DateTime unixEpoch = new DateTime(1970, 1, 1); double timeStamp = (value - unixEpoch).Ticks / 1000; return timeStamp; } 

JS

 var myDate = new Date( object.myEpochDate *1000); myDate.toUTCString().toLocaleString(); 

使用这种方法,您可以将纪元作为字符串传递到json中,然后像js中的日期一样处理它。

它与格式有关。 你绝对可以使用libs或插件,我选择保持它非常简单:

 function getFormattedDate(date) { var curr_date = date.getDate(); var curr_month = date.getMonth() + 1; //Months are zero based var curr_year = date.getFullYear(); return curr_date + "-" + curr_month + "-" + curr_year; } 

吻!