开发者

MVC Validation Attribute

How do you validate a class using Validation attributes when validating strongly typed view models.

Suppose you have a view model like so:

[PropertiesMustMatch("Admin.Password", "Admin.ConfirmPassword")]
public class AdminsEditViewModel
{
    public AdminsEditViewModel()
    {
        this.Admin = new Admin(); // this is an Admin class
    }

    public IEnumerable<SelectListItem> SelectAdm开发者_开发技巧insInGroup { get; set; }


    public IEnumerable<SelectListItem> SelectAdminsNotInGroup { get; set; }

    public Admin Admin { get; set; }
}

I get null exception when on this line of PropertiesMustMatchAttribute

object originalValue = properties.Find(OriginalProperty,  true /* ignoreCase */).GetValue(value);

since Password field is a property of Admin class and NOT AdminsEditViewModel. How do I make it so that it will go so many levels deep until it does find property of Admin in the ViewModel AdminsEditViewModel? thanks


You need to modify the PropertiesMustMatchAttribute class to parse the property name and search deeply.

This attribute is not part of the framework; it's included in the default MVC template (in AccountModels.cs)
You can therefore modify it to suit your needs.

Specifically, you would call name.Split('.'), then loop through splitted names and get the property values.
It would look something like

object GetValue(object obj, string properties) {
    foreach(strong prop in properties)
        obj = TypeDescriptor.GetProperties(obj)
                            .Find(prop, ignoreCase: true)
                            .GetValue(obj);
    }
    return obj;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜