繁体   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