Gant图表将以毫秒为单位的时间传递给MVC4控制器。下面的代码打印出1440190800000
$(".gantt").gantt({
onAddClick: function (dt, rowId) {
alert(dt);
window.location.href='NewBooking?' + $.param({
datetime: dt,
row: rowId
});
},
MVC4控制器具有签名:
public ActionResult NewBooking(DateTime datetime, string row)
{
var m = new NewBookingViewModel();
return View(m);
}
调用此控制器会导致错误
The parameters dictionary contains a null entry for parameter 'datetime' of non-nullable type 'System.DateTime' for method 'System.Web.Mvc.ActionResult NewBooking(System.DateTime, System.String)' in 'Eeva.Erp.Controllers.BookingController'. An optional parameter must be a
since milliseconds are not contverted to datetime.
如何在控制器代码或javascript中解决此问题以获得DateTime值?
毫秒不能代表日期。毫秒是用于测量持续时间的单位。因此,询问如何将持续时间转换为DateTime C#对象没有任何意义。
另一方面,自时间中某个固定日期(例如The Epoch)可以表示DateTime以来经过的毫秒数。我不熟悉您使用的客户端库以及这些毫秒代表什么,但是出于本示例的目的,让我们假设它们代表自1970年1月1日UTC时间以来经过的毫秒数。在这种情况下,您可以简单地将其转换为相应的DateTime对象:
public DateTime FromUnixTime(long unixTime)
{
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
return epoch.AddMilliseconds(unixTime);
}
进而:
public ActionResult NewBooking(long datetime, string row)
{
DateTime someDate = FromUnixTime(datetime);
var m = new NewBookingViewModel();
return View(m);
}
显然,可以进一步改进此代码,以便在自定义模型绑定程序中进行此转换,然后您的控制器操作可以直接采用DateTime对象参数。
因此,现在取决于您和您所使用的js库的文档,以详细说明将这些毫秒转换为DateTime的精确算法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句