【问题标题】:ASP.NET MVC enable custom validation attributesASP.NET MVC 启用自定义验证属性
【发布时间】:2013-10-28 14:58:42
【问题描述】:

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

仅供参考,我创建自己的属性的原因是因为我想从 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
}

【问题讨论】:

  • EditorFor 没有像你正在做的那样接受字符串的重载,msdn.microsoft.com/en-us/library/ee407414(v=vs.108).aspx
  • 糟糕,有点搞混了。这些是您可以传递给属性构造函数的属性。现在编辑我的问题。
  • 听起来 Sitecore 标记在这里不相关?

标签: asp.net-mvc-3 validation sitecore data-annotations


【解决方案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);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-04
    • 1970-01-01
    • 2014-11-03
    • 1970-01-01
    • 1970-01-01
    • 2013-11-12
    • 1970-01-01
    相关资源
    最近更新 更多