MVC Validation Attribute

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

Suppose you have a model of the form:

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

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


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

    public Admin Admin { get; set; }
}

I get a null exception when the property mustMatchAttribute in this line

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

because the Password field is a property of the Admin and NOT AdminsEditViewModel classes. How can I make it go through so many levels until I find the Admin property in the ViewModel AdminsEditViewModel? thank

+3
source share
1 answer

You need to change the class PropertiesMustMatchAttributeto parse the property name and search.

; MVC ( AccountModels.cs)
.

, name.Split('.'), .

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

Source: https://habr.com/ru/post/1785745/


All Articles