从模型中获取数据注释属性

let*_*mil 8 c# asp.net asp.net-mvc validationattribute data-annotations

我想创建自定义客户端验证器,但我希望通过业务逻辑层的Data Annotations属性定义验证规则.如何在运行时访问模型验证属性?

我想写'generator',它会转换这段代码:

public class LoginModel
{
    [Required]
    [MinLength(3)]
    public string UserName { get; set; }

    [Required]
    public string Password { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

进入这一个:

var loginViewModel= {
    UserName: ko.observable().extend({ minLength: 3, required: true }),
    Password: ko.observable().extend({ required: true })
};
Run Code Online (Sandbox Code Playgroud)

但当然不是来自.cs来源.=)

也许反思?

UPD

我发现了这个方法:MSDN.但无法理解如何使用它.

Dam*_*iel 13

这是如何做到这一点的通用方法:

private string GenerateValidationModel<T>()
{
    var name = typeof(T).Name.Replace("Model", "ViewModel");
    name = Char.ToLowerInvariant(name[0]) + name.Substring(1);

    var validationModel = "var " + name + " = {\n";

    foreach (var prop in typeof(T).GetProperties())
    {
        object[] attrs = prop.GetCustomAttributes(true);
        if (attrs == null || attrs.Length == 0)
            continue;

        string conds = "";

        foreach (Attribute attr in attrs)
        {
            if (attr is MinLengthAttribute)
            {
                conds += ", minLength: " + (attr as MinLengthAttribute).Length;
            }
            else if (attr is RequiredAttribute)
            {
                conds += ", required: true";
            }
            // ...
        }

        if (conds.Length > 0)
            validationModel += String.Format("\t{0}: ko.observable().extend({{ {1} }}),\n", prop.Name, conds.Trim(',', ' '));
    }

    return validationModel + "};";
}
Run Code Online (Sandbox Code Playgroud)

用法:

string validationModel = GenerateValidationModel<LoginModel>();
Run Code Online (Sandbox Code Playgroud)

输出:

var loginViewModel = {
    UserName: ko.observable().extend({ minLength: 3, required: true}),
    Password: ko.observable().extend({ required: true}),
};
Run Code Online (Sandbox Code Playgroud)

缓存输出是个好主意