![](/img/trans.png)
[英]asp.net mvc controller does not recognize DateTime url parameter?
[英]How to convert milliseconds to DateTime in ASP.NET MVC controller parameter
甘特圖將時間(以毫秒為單位)傳遞給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的精確算法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.