2013-09-10 35 views
3

我試圖獲得文化特定數據註釋。文化特定數據註釋

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

我認爲這可行。所以在美國它會顯示DD/MM/yyyy,在歐洲它會顯示MM/DD/YYYY。

爲了測試這個,我將默認的chrome語言設置爲英語(UK)並重新啓動瀏覽器。

雖然我仍然使用美國格式,這讓我相信我的DataFormatString不尊重文化。

如何解決這個問題?我是否也可以減少一年,所以它只是「YY」而不是「YYYY」?

回答

3

這種格式是文化特定的。你一定在做錯事。

  1. 創建一個使用默認模板
  2. 一個新的ASP.NET MVC應用程序添加視圖模型:

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

    public class HomeController : Controller 
    { 
        public ActionResult Index() 
        { 
         return View(new MyViewModel 
         { 
          Date = DateTime.Now, 
         }); 
        } 
    } 
    
  4. 和一個視圖:

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

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

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

enter image description here

所以一定要在這種情況下,文化設置爲自動

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

然後瀏覽器會發送正確的Accept-Language請求頭,看起來像這樣:

enter image description here

,顯然預期的結果將被格式化:

enter image description here

+0

我沒有在web.config中設置我的culture =「auto」。謝謝! – Nate

2

你有實際設置當前的文化,MVC框架沒有按」請自動設置它(請記住,頁面的語言可能取決於URL等因素,而不僅僅是瀏覽器設置。

要設置文化,請使用Thread.CurrentThread.CurrentCultureThread.CurrentThread.CurrentUICulture。您可以從HttpRequest.UserLanguages獲取瀏覽器設置(請記住,該值只是通過HTTP請求發送的值)。

編輯

this answer,似乎還有的方式來指導ASP。Net根據HTTP請求頭設置語言(將web.config globalization - >「culture」和「uiCulture」設置爲「auto」)。