2013-10-28 54 views
1

我正在尝试为ASP.NET MVC项目创建我自己的模型验证属性。我遵循this question的建议,但无法看到如何让@Html.EditorFor()识别我的自定义属性。我是否需要在web.config的某处注册我的自定义属性类?对此this answer的评论似乎在提出同样的问题。ASP.NET MVC启用自定义验证属性

仅供参考我创建自己的属性的原因是因为我想从Sitecore中检索字段显示名称和验证消息,并且不想真正想用大量静态方法创建类的路径来表示每个文本属性,这是我必须做的,如果我是用

public class MyModel 
{ 
    [DisplayName("Some Property")] 
    [Required(ErrorMessageResourceName="SomeProperty_Required", ErrorMessageResourceType=typeof(MyResourceClass))] 
    public string SomeProperty{ get; set; } 
} 

public class MyResourceClass 
{ 
    public static string SomeProperty_Required 
    { 
     get { // extract field from sitecore item } 
    } 

    //for each new field validator, I would need to add an additional 
    //property to retrieve the corresponding validation message 
} 
+1

有没有EditorFor的重载acepts串像你正在做的,http://msdn.microsoft.com/en-us/library/ee407414(v=vs.108).aspx – Fals

+0

糟糕,在那里有点混。那些属性可以传递给属性构造函数。现在编辑我的问题。 –

+0

听起来像Sitecore标签在这里不相关? –

回答

1

这个问题已经在这里找到答案:

How to create custom validation attribute for MVC

为了让您的自定义验证器属性起作用,您需要注册它。这可以在Global.asax中做下面的代码:

public void Application_Start() 
{ 
    System.Web.Mvc.DataAnnotationsModelValidatorProvider.RegisterAdapter(
     typeof (MyNamespace.RequiredAttribute), 
     typeof (System.Web.Mvc.RequiredAttributeAdapter)); 
} 

(如果你使用WebActivator你可以把上面的代码放到一个启动类在App_Start文件夹。)

我的自定义属性类看起来是这样的:

public class RequiredAttribute : System.ComponentModel.DataAnnotations.RequiredAttribute 
{ 
    private string _propertyName; 

    public RequiredAttribute([CallerMemberName] string propertyName = null) 
    { 
     _propertyName = propertyName; 
    } 

    public string PropertyName 
    { 
     get { return _propertyName; } 
    } 

    private string GetErrorMessage() 
    { 
     // Get appropriate error message from Sitecore here. 
     // This could be of the form "Please specify the {0} field" 
     // where '{0}' gets replaced with the display name for the model field. 
    } 

    public override string FormatErrorMessage(string name) 
    { 
     //note that the display name for the field is passed to the 'name' argument 
     return string.Format(GetErrorMessage(), name); 
    } 
}