【问题标题】:Dataannotations validation数据注释验证
【发布时间】:2011-05-05 14:04:16
【问题描述】:

在 asp.net mvc3 上,我使用数据注释进行验证。我用一个简单的 if(ModelState.IsValid) 控制我的控制器上的验证。如何在一个简单的类而不是控制器中控制这些验证?

谢谢!

【问题讨论】:

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


    【解决方案1】:
    【解决方案2】:

    这几乎就是 MVC 验证器在幕后所做的:

    这将遍历所有注释并确定是否有任何错误并将它们添加到错误集合中。最好把它放在一个基类中,然后让所有其他类继承它。如果GetErrors().Any()返回true,则模型无效。

     public IEnumerable<ErrorInfo> GetErrors() {
                return from prop in TypeDescriptor.GetProperties(this).Cast<PropertyDescriptor>()
                       from attribute in prop.Attributes.OfType<ValidationAttribute>()
                       where !attribute.IsValid(prop.GetValue(this))
                       select new ErrorInfo(prop.Name, attribute.FormatErrorMessage(string.Empty));
            }
    

    错误信息类:

    public class ErrorInfo{
    public string Name { get; set; }
    public string FormatErrorMessage { get; set; }    
    
    public ErrorInfo(string name, string formatErrorMessage){
        Name = name;
        FormatErrorMessage = formatErrorMessage;
    
     }
    }
    

    【讨论】:

      【解决方案3】:

      在此回答(使用 .net 4): Using ASP.Net MVC Data Annotation outside of MVC

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-08
        • 2011-04-24
        相关资源
        最近更新 更多