Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
278 views
in Technique[技术] by (71.8m points)

c# - Get Data Annotations attributes from model

I want to create custom client-side validator, but I want define validation rules via Data Annotations attributes at business logic layer. How can I access model validation attributes in runtime?

I want to write 'generator', which will convert this code:

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

    [Required]
    public string Password { get; set; }
}

into this one:

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

But not from .cs sources, of course. =)

Maybe reflection?

UPD

I've found this method: MSDN. But can't understand how to use it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is the universal way how to do this:

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

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

    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("{0}: ko.observable().extend({{ {1} }}),
", prop.Name, conds.Trim(',', ' '));
    }

    return validationModel + "};";
}

Usage:

string validationModel = GenerateValidationModel<LoginModel>();

Output:

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

It's good idea to cache the output


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...