【问题标题】:How do I change the default input format on the DateTime model binder in .Net MVC?如何更改 .Net MVC 中 DateTime 模型绑定器的默认输入格式?
【发布时间】:2009-07-14 12:05:39
【问题描述】:

我有一个相当标准的 .Net MVC 控制器方法:

public ActionResult Add(Customer cust) {  
  //do something...  
  return View();
}

客户是这样的:

public class Customer {
  public DateTime DateOfBirth { get; set; }
  //more stuff...
}

还有一个页面包含:

<div><%= Html.TextBox("DateOfBirth") %></div>

问题是我的网站位于美国服务器上,因此 cust.DateOfBirth 被解析为美国格式 MM/dd/yyyy。但是,我希望用户以英国格式 dd/MM/yyyy 输入他们的出生日期。

我可以更改 DateTime ModelBinder 上的默认输入格式还是必须创建自己的自定义 ModelBinder?

【问题讨论】:

    标签: c# asp.net-mvc


    【解决方案1】:

    您可以在 web.config 文件或页面级别更改文化。但是,如果您只想更改日期格式而不是文化的其他方面,则可能需要您通过 global.asax 或通用基本控制器中的代码修改当前文化的 DateTimeFormat 并将其设置为 DateTimeFormat for "en -GB"。

    Reference

    设置 UI 文化和文化为 所有页面,添加一个全球化部分 到 Web.config 文件,然后设置 uiculture 和文化属性, 如下例所示:

    <globalization uiCulture="en" culture="en-GB" />

    设置UI文化和文化 一个单独的页面,设置文化 @Page 的 UICulture 属性 指令,如下图所示 示例:

    <%@ Page UICulture="en" Culture="en-GB" %>

    让 ASP.NET 设置 UI 文化和 文化到第一语言 在当前浏览器中指定 设置,将 UICulture 和 Culture 设置为 汽车。或者,您可以设置此 auto:culture_info_name 的值,其中 culture_info_name 是文化名称。 有关文化名称的列表,请参阅 文化信息。您可以进行此设置 在@ Page 指令中或 Web.config 文件。

    替代方案:

     CultureInfo.CurrentUICulture.DateTimeFormat
         = CultureInfo.CurrentCulture.DateTimeFormat
         = new CultureInfo( "en-GB", false ).DateTimeFormat;
    

    【讨论】:

    • 谢谢,我无法让@Page 指令工作,我正在使用母版页并将其放置在视图中。有任何想法吗? web.config 中的 标记运行良好,我现在已经使用它,但我希望将来能逐页运行。
    【解决方案2】:

    您可以更改不同快捷键模式的含义。在您的情况下,它将是短日期模式或“d”。如果您通常喜欢 en-US 文化,但只需将日期时间模式更改为较短的日期时间,您可以将其添加到 Global.asax

    protected void Application_BeginRequest(Object sender, EventArgs e)
    {
        CultureInfo ci = new CultureInfo("en-US");
        ci.DateTimeFormat.SetAllDateTimePatterns(
            new string[] { "dd/MM/yyyy" },
            'd'
        );
        System.Threading.Thread.CurrentThread.CurrentCulture = ci;
        System.Threading.Thread.CurrentThread.CurrentUICulture = ci;
    }
    

    第一个数组是支持的日期时间格式,第二个字符是您要替换的模式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-14
      • 2020-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-22
      • 1970-01-01
      相关资源
      最近更新 更多