簡體   English   中英

將Date對象從javascript傳遞到asp.net mvc控制器

[英]Pass Date object from javascript to asp.net mvc controller

我在客戶端有一個Date變量,我想將Date變量傳遞給服務器端的控制器。 我已作為普通字段通過,日期默認為01-01-0001 12:00:00 AM。

幫助我將日期字段轉換為正確的格式。

ASP.NET MVC期望DateTime值的格式為Thread.CurrentLanguage。 請檢查您使用的語言。

之所以這樣,是因為用戶可能會在文本框中輸入日期,然后他們將輸入其語言的格式。

就像Pieter所說的那樣:一種簡單的方法是在這種情況下使用字符串。

另一種方法是使用

protected void Application_BeginRequest(object sender, EventArgs e)
{
    Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
}

在Global.Asax中。

在發生ModelBinding之后,您可以在過濾器中切換回用戶的語言:

    public override void OnActionExecuting(ActionExecutingContext filterContext)
     {
             string language = //find a way to get the language - I have it in the route
             Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(language);
             Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(language);
         base.OnActionExecuting(filterContext)
     }

這種方式存在一些風險,但是如果modelBinding使用InvariantCulture(在路由中使用十進制值,在路由中使用日期時間...),在很多情況下,我發現它更容易。

我認為將日期的字符串表示形式傳遞給ASP.NET MVC操作並嘗試使用DateTime.TryParse(..)進行解析將是最簡單的。

[HttpPost]
public ActionResult(string dateTimeString)
{
    DateTime tempDateTime;
    if(DateTime.TryParse(dateTimeString, out tempDateTime))
    {
       //Handle
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM