2012-06-11 19 views
2

我正在使用MVC3和C#開發多租戶應用程序。 我正在使用帶驗證屬性裝飾的屬性的模型類。 我想要做的是在客戶端和服務器端返回特定於租戶的錯誤消息。MVC 3多租戶應用程序驗證屬性錯誤消息

有沒有什麼辦法可以在運行時爲每個請求掛接mvc驗證和呈現/返回租戶特定消息?

我的代碼片斷是非常sipmle:

型號:

public class TestModel 
{ 
    [Required(ErrorMessageResourceName="errormessage",  ErrorMessageResourceType=typeof(Global)] 
    [RegularExpression(@"\d+", ErrorMessageResourceName="errormessagedigit", ErrorMessageResourceType=typeof(Global)] 
    public string TestProperty {get; set;} 
} 

查看:

@using(Html.BeginFrom()) 
{ 
    @Html.ValidationSummary(false, "")<br/> 
    @Html.TextBoxFor(x => x.TextProperty)<br /> 
    <input type="submit" value="submit" /> 
} 

回答

0

一種方法是創建一組custom validation attributes每個從的一個繼承現有的驗證屬性(例如MyRequired),但包含注入租戶特定錯誤消息的代碼。

0

我想我找出了我的問題的答案。

您需要從每個現有屬性繼承並重寫FormatErrorMessage方法。 在此方法中,您可以訪問包含原始驗證屬性錯誤消息的ErrorMessageString屬性。您可以創建請求/租戶特定的邏輯來格式化/覆蓋錯誤消息。

看起來像這種方法可以返回/呈現每個請求錯誤消息的自定義。

代碼片段:

public class RequiredAttributeTest:RequiredAttribute 
{ 

public override string FormatErrorMessage(string name)   
    { 
     // code to return request/tenant specific error message  
     return GetTenantError(ErrorMessageString, name); 
    } 
} 

public class RegularExpressionAtributeTest:RegularExpressionAttribute 
    { 
    public RegularExpressionAtributeTest(string pattern) : base(pattern) { } 

public override string FormatErrorMessage(string name) 
    {   
     // code to return request/tenant specific error message  
     return GetTenantError(ErrorMessageString, name); 
    } 
    } 

的Global.asax.cs

protected void Application_Start() 
{ 
… 
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RequiredAttributeTest), typeof(RequiredAttributeAdapter)); 
DataAnnotationsModelValidatorProvider.RegisterAdapter 
(typeof(RegularExpressionAtributeTest), typeof(RegularExpressionAttributeAdapter)); 
… 
} 
+0

格式使用工具欄的代碼。 – jgauffin