Cultural specific data annotations

前端 未结 2 1881
無奈伤痛
無奈伤痛 2021-01-21 02:34

I\'m trying to get cultural specific data annotations.

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

I though

相关标签:
2条回答
  • 2021-01-21 03:14

    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>
    

    enter image description here

    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:

    enter image description here

    and obviously the result will be formatted as expected:

    enter image description here

    0 讨论(0)
  • 2021-01-21 03:25

    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").

    0 讨论(0)
提交回复
热议问题