2011-12-19 23 views
8

我們在數據庫中有本地化的字符串,並且想知道extending the ASP.NET Resource Provider Model是否可以與ASP.NET MVC 3 Razor視圖引擎一起使用。ASP.NET MVC 3: - 使用數據庫而不是資源文件作爲本地化存儲

請讓我知道ASP.NET MVC 3 Razor視圖引擎是否支持從數據庫中檢索本地化的字符串,只要我們擴展了ASP.NET資源提供程序模型。或者它只適用於Classic ASP.NET,而不適用於ASP.NET MVC。

謝謝

SatyaprakashĴ

+0

[ASP.NET MVC 2 Localization/Globalizatio n存儲在數據庫中嗎?](http://stackoverflow.com/questions/2568129/asp-net-mvc-2-localization-globalization-stored-in-the-database) – jrummell 2011-12-19 14:50:05

回答

9

到目前爲止,我已經找到了乾淨的解決方案是:http://www.codeproject.com/Tips/514321/A-Simple-and-Effective-Way-to-Localize-ASP-Net-MVC

歡迎評論/反饋。

編輯1:根據評論,我添加了代碼示例並將鏈接用作參考。

我創建了一個customDataAnnotationsProvider類:

public class CustomDataAnnotationsProvider: DataAnnotationsModelMetadataProvider 
{ 
    private ResourceManager resourceManager = new ResourceManager(); 
    protected override ModelMetadata CreateMetadata(
         IEnumerable<Attribute> attributes, 
         Type containerType, 
         Func<object> modelAccessor, 
         Type modelType, 
         string propertyName) 
    { 
     string key = string.Empty; 
     string localizedValue = string.Empty; 


     foreach (var attr in attributes) 
     { 
      if (attr != null) 
      { 
       if (attr is DisplayAttribute) 
       { 
        key = ((DisplayAttribute)attr).Name; 
        if (!string.IsNullOrEmpty(key)) 
        { 
         localizedValue = resourceManager.GetLocalizedText(key); 
         ((DisplayAttribute)attr).Name = localizedValue; 
        } 
       } 
       else if (attr is ValidationAttribute) 
       { 
        key = ((ValidationAttribute)attr).ErrorMessage; 
        if (!string.IsNullOrEmpty(key)) 
        { 
         localizedValue = resourceManager.GetLocalizedText(key); 
         ((ValidationAttribute)attr).ErrorMessage = localizedValue; 
        } 
       } 
      } 
     } 
     return base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName); 
    } 
} 

然後,我在Global.asax中

引用上ApplicationStart自定義提供
ModelMetadataProviders.Current = new Project.Web.Helpers.CustomDataAnnotationsProvider(); 

你不必改變你的模型,並可以使用顯示註解:

[Display(Name = "CustomerAccountNumber")] 
public string CustomerAccountNumber { get; set; } 
+0

請注意,僅提供鏈接的答案是不鼓勵的,引用會隨着時間的推移而變得陳舊。考慮在這裏添加一個獨立的簡介,保持鏈接作爲參考。 – kleopatra 2013-03-20 12:24:04

相關問題