2011-10-30 48 views
0

我需要一個用於ASP.NET MVC3模型驗證邏輯的解決方案。我有一個自定義的本地化解決方案,我傳遞的所有字符串通過方法轉換,類似的東西:MVC3修改模型驗證元數據和錯誤消息

​​

注:我不知道,但我認爲這種做法源於QT localizastion邏輯。 WordPress也在使用smillar技術。

當我嘗試將此溶液模型驗證屬性這樣的:

[Required(ErrorMessage = Localizer.Translate("Please enter detail text!"))] 
    [DisplayName(Localizer.Translate("Detail"))] 
    public string Details { get; set; } 

編譯器給我此錯誤:

錯誤1的屬性參數必須是常量表達式的typeof表達或陣列創建一個屬性參數類型的表達式...

所以,我試圖修改錯誤消息和DisplayName屬性,但我不能。

有沒有辦法做到這一點?如果有的話,它可能是我的生命保護:)

回答

0

我有一個解決方法創建我的自定義@ Html.LabelFor()和@ html.DescriptionFor()助手。

我的幫助:

namespace MyCMS.Helpers 
{ 
public static class Html 
{ 
    public static MvcHtmlString DescriptionFor<TModel, TValue>(
     this HtmlHelper<TModel> self, 
     Expression<Func<TModel, TValue>> expression) 
    { 
     var metadata = ModelMetadata.FromLambdaExpression(expression, self.ViewData); 
     var description = Localizer.Translate(metadata.Description); 

     return MvcHtmlString.Create(string.Format(@"<span class=""help-block"">{0}</span>", description)); 
    } 

    public static MvcHtmlString LabelFor<TModel, TValue>(
     this HtmlHelper<TModel> self, 
     Expression<Func<TModel, TValue>> expression, 
     bool showToolTip 
    ) 
    { 
     var metadata = ModelMetadata.FromLambdaExpression(expression, self.ViewData); 
     var name = Localizer.Translate(metadata.DisplayName); 

     return MvcHtmlString.Create(string.Format(@"<label for=""{0}"">{1}</label>", metadata.PropertyName, name)); 
    } 
} 
} 

我的看法是:

@using MyCMS.Localization; @using MyCMS.Helpers;

<div class="clearfix "> 
     @Html.LabelFor(model => model.RecordDetails.TitleAlternative) 
     <div class="input"> 
      @Html.TextBoxFor(model => model.RecordDetails.TitleAlternative, new { @class = "xxlarge" }) 
      @Html.ValidationMessageFor(model => model.RecordDetails.TitleAlternative) 
      @Html.DescriptionFor(model => model.RecordDetails.TitleAlternative) 
     </div> 
    </div> 

,我可以用我的定位方法:)

謝謝大家再次...

1

您可以使用resource files to do localization

將資源文件(可以通過Visual Studio使用「添加新項」嚮導 - 可以將其稱爲MyResourcesType.resx)添加到項目中。然後添加您的驗證消息,如下所示:

[Required(
    ErrorMessageResourceType = typeof(MyResourcesType), 
    ErrorMessageResourceName = "MyMessageIdOnTheResourcesFile")] 

從現在起改變語言只是一個添加新資源文件的問題。檢查this question's first answer

順便說一下不要使用DisplayNameAttribute,而是DisplayAttributeSystem.ComponentModel.DataAnnotations命名空間。這是MVC使用的屬性,您也可以對其進行本地化:

[Display(
    ResourceType = typeof(MyResourcesType), 
    Name = "MyPropertyIdOnResourcesFile_Name", 
    ShortName = "MyPropertyIdOnResourcesFile_ShortName", 
    Description = "MyPropertyIdOnResourcesFile_Description")] 
+0

我不會僅僅說你*可*用於該用途的資源文件;這就是你認爲在.NET中處理本地化的方式。 – Aaronaught

+0

謝謝你們,我在下面發佈了我的解決方案 – Orhaan

0

方法屬性的工作原理是它們被靜態編譯到代碼中。因此,使用屬性時不能有任何動態功能。

Jota的回答是推薦的做事方式,但是如果您決定使用自己的解決方案,您可以創建自己的屬性,並在該屬性中添加查找消息的代碼。