asp.net-mvc - 从 ASP.NET MVC 3 中的必需属性继承时,客户端验证不起作用?

标签 asp.net-mvc asp.net-mvc-3 data-annotations

我在 ASP.NET MVC3 中创建了一个这样的继承属性:

public sealed class RequiredFromResourceAttribute : RequiredAttribute
{
    public RequiredFromResourceAttribute(string errorResourceName, string errorResourceTypeName)
    {
        this.ErrorMessageResourceName = errorResourceName;
        this.ErrorMessageResourceType = Type.GetType(errorResourceTypeName);
    }
}

并像这样使用它:
[RequiredFromResource("Title", "Resources.Resource, MyProject.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null")]
public string Title { get; set; }

它不起作用,MVC 忽略了它。然后我创建一个更简单的类,它只是从 RequiredAttribute 继承的,如下所示:
public class MyRequiredAttribute : RequiredAttribute
{
}

我就像我说的那样使用它。但它再次不起作用。

尽管如此,所有这些方式都可以完美地应用于“DisplayNameAtrribute”。

问题是什么?

最佳答案

它只是不适用于继承属性的客户端验证。原因是 MVC 在将服务器端属性映射到客户端验证行为时使用了严格的类型相等。

要解决此问题,您需要自定义属性来实现 IClientValidatable :

public class MyRequiredAttribute : IClientValidatable {
    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) {
         yield return new ModelClientValidationRequiredRule();
    }
}

关于asp.net-mvc - 从 ASP.NET MVC 3 中的必需属性继承时,客户端验证不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4749657/

相关文章:

c# - IPagedList 实现了 IList 接口(interface),但是

asp.net - jQuery UI DatePicker 图像未显示

c# - 从 session 中存储/检索动态对象后检索属性

c# - 使用routes.maproute和参数

c# - Aspx 到 Razor 语法转换器?

asp.net-mvc - 如何使用多个项目将大型 ASP.NET MVC 站点分成多个部门?

asp.net-mvc - 从 Controller 返回 html 字符串并显示在 View 中

c# - 如何在 C# 中使用 EmailAddressAttribute 验证字符串列表?

entity-framework - 为什么 EF Code First [InverseProperty] 属性在与 [ForeignKey] 属性一起使用时无法工作?

ajax - ASP.Net MVC : Can you use Data Annotations/Validation with an AJAX/jQuery call?