Cultural specific data annotations

雨燕双飞 提交于 2019-12-04 04:27:35

问题


I'm trying to get cultural specific data annotations.

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

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

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

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

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


回答1:


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

  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; }
    }
    
  3. A controller:

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

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

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:




回答2:


You have to actually set the current culture, the MVC framework doesn't set it automatically (remember that a page's language might depend on factors like the URL, not just the browser settings.

To set the culture, use Thread.CurrentThread.CurrentCulture and Thread.CurrentThread.CurrentUICulture. You can get the browser settings from HttpRequest.UserLanguages (keep in mind that this value is just what comes through the HTTP request).

Edit

Per this answer, it seems there is a way to instruct ASP.Net to set the language based on the HTTP request header (set web.config globalization -> "culture" and "uiCulture" to "auto").



来源:https://stackoverflow.com/questions/18728505/cultural-specific-data-annotations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!