.NET MVC4 實訓記錄之六(利用ModelMetadata實現資源的自主訪問)

來源:互聯網
上載者:User

標籤:style   blog   http   color   os   使用   io   strong   ar   

  上一篇我們已經實現自訂資源檔的訪問,該篇我們使用它配合ModelMetadata實現資源檔的自主訪問。這樣做是為了我們能更簡單的用MVC原生的方式使用資源檔。由於我的文章旨在記錄MVC項目的實現,因此不做架構底層實現方面的講解(其實考慮到自己的能力,也不能為大家講解的多麼深入。如需要更深入的瞭解MVC底層實現,請自行搜尋。在這裡我推薦蔣金楠(Artech)老師的相關博文)。

  對於使用EF,我們不得不知道System.ComponentModel.DataAnnotations。DataAnnotations下定義了一系列的Attribute,用於我們的屬性欄位註解方案。例如DisplayAttribue,用於定義屬性所顯示的名稱的文本資訊。RequiredAttribute用於定義屬性是否必填,以及必填校正失敗後的提示資訊。它們是我們最常用的註解屬性中的兩個,我們一般都使用它們來描述我們的欄位在使用者介面的顯示效果。例如我們在UserProfile定義的UserName屬性上引入如下Attribute:

1         [Column(Order = 1)]2         [Required(ErrorMessage = "The User Name is required!")]3         [Display(Name = "Filed: User Name")]4         public string UserName { get; set; }
View Code

  在EditUser.cshtml視圖中已如下方式顯示該欄位:

1 @using (Html.BeginForm("EditUser", "Account", FormMethod.Post))2 {3     <p>@Html.LabelFor(p=>p.UserName)</p>  4     <p>@Html.TextBoxFor(p=>p.UserName)</p>5     6     <input type="submit" value="提交" />7 }
View Code

  運行項目並開啟該頁面,直接點擊提交按鈕,會得到如下的顯示效果:

  這說明MVC架構已經幫我們將欄位註冊的UI顯示資訊列印到當前頁面。 可是,我們的項目本身的資源語言未定,或者說,需要多語言支援,這個方案就有些牽強。雖然System.ComponentModel.DataAnnotations已經提供了使用自訂資源的相關定義,但都是針對.resx或者已經進行編譯過的資源類。無法使用我們自訂的XML資源檔。對此我們有兩種方案對其進行改造,以使用我們自訂的資源檔。它們分別是:自訂CustmorDisplayAttribute,改造MVC架構。第一個方案的使用方式與上面例子相同,只不過我們需要為每個需要顯示在頁面上的Field都引入自訂的屬性注釋。後兩者則更加便捷,無需對類型定義做出任何改變。在這裡,我們不討論第一種方案。

  第二種方案屬於“進階方案”,也就是說從設計層面解決這個問題。

  針對這種方案,我們先要瞭解ModelMetadata,以及ModelMetadataProvider。在此僅附上相關的代碼,不做深入討論。

  首先,是要定義我們自己的ModelMetadataProvider。

 1     public class AppModelMetadataProvider : CachedDataAnnotationsModelMetadataProvider 2     { 3         protected override CachedDataAnnotationsModelMetadata CreateMetadataFromPrototype(CachedDataAnnotationsModelMetadata prototype, Func<object> modelAccessor) 4         { 5             CachedDataAnnotationsModelMetadata metadata = base.CreateMetadataFromPrototype(prototype, modelAccessor); 6             if (metadata.ContainerType != null && !String.IsNullOrEmpty(metadata.PropertyName)) 7             { 8                 metadata.DisplayName = Resource.GetDisplay(string.Format("{0}.{1}", metadata.ContainerType.Name, metadata.PropertyName)); 9             }10             return metadata;11         }12     }
View Code

  我們僅重寫了CachedDataAnnotationsModelMetadataProvider類型中的CreateMetadataFromPrototype方法,在該方法中,我們將Model(這裡的Model並非只是頁面定義的強型別,它也可以是強型別的屬性。當頁面初始化階段,需要擷取當前頁面的模型類型。因此,這個時候的Model就是頁面綁定的強型別執行個體,其ContainerType為空白。但當頁面訪問到此類型的屬性,例如 p => p.UserName,此時的Model就是UserName,ContainerType則為頁面綁定的強型別)的DisplayName屬性進行修改。原本DisplayName會返回屬性的DisplayAttribute注釋中定義的資源內容,現在我們將其修改為從自訂資源檔中擷取內容(注意:資源的鍵要嚴格按照“容器類型名.屬性名稱”進行定義)。

  最後,在Global檔案的Application_Start()中添加代碼以使用我們自訂的Provider。

 1     protected void Application_Start() 2         { 3             AreaRegistration.RegisterAllAreas(); 4  5             WebApiConfig.Register(GlobalConfiguration.Configuration); 6             FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 7             RouteConfig.RegisterRoutes(RouteTable.Routes); 8             BundleConfig.RegisterBundles(BundleTable.Bundles); 9             AuthConfig.RegisterAuth();           10 11             Bootstrapper.Initialise();  //初始化IOC容器12 13             ModelMetadataProviders.Current = new AppModelMetadataProvider();14         }
View Code

  在視圖檔案中,我們修改成利用MVC自訂的HtmlHelper顯示欄位名。如下:

1 @using (Html.BeginForm("EditUser", "Account", FormMethod.Post))2 {3     @Html.ValidationSummary()4     <div>5         @Html.LabelFor(p => p.UserName)6         @Html.TextBoxFor(p => p.UserName)       7     </div>8     <input type="submit" value="提交" />9 }
View Code

  第二種方案已完成。運行項目,觀察一下我們的頁面變化。然後修改一下資源檔中的內容,資源檔的修改也能被立刻應用,而不需要重新編譯。

  然後我們在UserProfile類型定義中添加一個Address類型的屬性。

 1     [Table("UserProfile")] 2     public class UserProfile 3     { 4         //無關代碼省略...... 5  6         public int? AddressId { get; set; } 7  8         [ForeignKey("AddressId")] 9         public Address Address { get; set; }10     }11 12     [Table("Address")]13     public class Address: BaseEntity<int>14     {15         public string City { get; set; }16     }
View Code

  修改EditUser視圖,如下:

 1 @using (Html.BeginForm("EditUser", "Account", FormMethod.Post)) 2 { 3     @Html.ValidationSummary() 4     <div> 5         @Html.LabelFor(p => p.UserName) 6         @Html.TextBoxFor(p => p.UserName) 7         @Html.LabelFor(p => p.Address.City) 8         @Html.TextBoxFor(p => p.Address.City) 9     </div>10     <input type="submit" value="提交" />11 }
View Code

  在資源檔中添加

1 <resource key="Address.City" value="City"/>

  那麼運行項目開啟頁面後,可以看到如下效果:

  

  導覽屬性的自訂資源資訊也會被顯示。這裡就可以看出p => p.Address.City時,Provider中的ContainerType則為Address的實際類型,ModelMetadata中的Model則為實際上要顯示的子類型的屬性。

  問題:

  我們通過對ModelMetadata內部的屬性進行修改,從而實現自訂資源的使用。這種方式屬於高階應用,有必要深入瞭解MVC的模型繫結相關的知識。本人在完成這篇文章的時候,耗費了相當長的時間(粗略統計大概有3天時間)。主要是想解決多個同類型屬性該如何顯示不同的自訂資源。例如在UserProfile類型中定義兩個同為Address類型的屬性,分別為UserAddress、和CompanyAddress。若同時在頁面顯示這兩個屬性的City名稱,則顯示的內容是相同的,都指向同一個資源:

<resource key="Address.City" value="City"/>。但始終未能在第二種方案下找到適合的解決辦法。希望有達人能為在下解惑,不勝感激!!!

  下期預告:第三中方案解決同類型導覽屬性顯示不同的自訂資源。

  

 

.NET MVC4 實訓記錄之六(利用ModelMetadata實現資源的自主訪問)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.