I\'m trying to get cultural specific data annotations.
[DisplayFormat(DataFormatString = \"{0:d}\")]
public DateTime Date{ get; set; }
I though
This format is culture specific. You must be doing something wrong.
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)
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:
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").