文化的具体数据注解 [英] Cultural specific data annotations

查看:161
本文介绍了文化的具体数据注解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让文化的特定数据的注释。

I'm trying to get cultural specific data annotations.

[DisplayFormat(DataFormatString = "{0:d}")]
public DateTime Date{ get; set; }

我认为这是可行的。因此,在美国,它会显示DD / MM / YYYY,并在欧洲,它会显示MM / DD / YYYY。

I thought this would work. So in the us it would show DD/MM/yyyy and in europe it would show MM/DD/YYYY.

要测试这一点,我将我的默认铬语言为英语(UK)并重新启动浏览器。

To test this, I set my default chrome language to English (UK) and restarted the browser.

我仍然得到美国的格式,虽然,这使我相信我的DataFormatString是不尊重的文化。

I'm still getting the US format though, which leads me to believe my DataFormatString isn't respecting cultures.

如何解决这个问题?我还可以削减年度所以它只是YY,而不是YYYY?

How to I fix this? Can I also cut of the year so it's just "yy" instead of "yyyy"?

推荐答案

这格式是特定文化的。你一定是做错了什么。

This format is culture specific. You must be doing something wrong.


  1. 创建使用默认模板创建一个新的ASP.NET MVC应用程序

  2. 添加视图模型:

  1. Create a new ASP.NET MVC application using the default template
  2. Add a view model:

public class MyViewModel
{
    [DisplayFormat(DataFormatString = "{0:d}")]
    public DateTime Date { get; set; }
}


  • 一个控制器:

  • A controller:

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View(new MyViewModel
            {
                Date = DateTime.Now,
            });
        }
    }
    


  • 和一个观点:

  • And a view:

    @using MvcApplication1.Models
    @model MyViewModel
    
    @Html.DisplayFor(x => x.Date)
    


  • 现在力的文化在你的web.config一些特定的文化:

    Now force the culture in your web.config to some specific culture:

    <system.web>
        <globalization culture="fr-FR"/>
        ...
    </system.web>
    

    所以一定要在这种情况下,文化设置为自动

    So make sure you set the culture to auto in this case:

    <system.web>
        <globalization culture="auto"/>
        ...
    </system.web>
    

    然后,浏览器会发送正确的接受语言请求头,看起来像这样:

    Then the browser will send the proper Accept-Language request header that looks like this:

    和明显预期的结果将被格式化:

    and obviously the result will be formatted as expected:

    这篇关于文化的具体数据注解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆