多租户应用程序的MVC 3验证属性错误消息

时间:2012-06-11 02:53:32

标签: asp.net asp.net-mvc-3

我正在使用MVC3和C#开发Multi Tenant应用程序。 我正在使用带有验证属性的属性的模型类。 我想要做的是在客户端和服务器端返回特定于租户的错误消息。

有没有办法在运行时为每个请求挂钩mvc验证并呈现/返回特定于租户的消息?

我的代码片段非常简洁:

型号:

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" />
}

2 个答案:

答案 0 :(得分:0)

一种方法是创建一组custom validation attributes,每个都继承自现有验证属性之一(例如MyRequired),但包含注入租户特定错误消息的代码。

答案 1 :(得分: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));
…
}