Cultural specific data annotations

前端 未结 2 1882
無奈伤痛
無奈伤痛 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:

    
        
        ...
    
    

    enter image description here

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

    
        
        ...
    
    

    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

提交回复
热议问题