Class/Model Level Validation (as opposed to Property Level)? (ASP.NET MVC 2.0)

后端 未结 6 2168
忘掉有多难
忘掉有多难 2020-12-14 10:31

Basically, what the title says. I have several properties that combine together to really make one logical answer, and i would like to run a server-side validation code (tha

6条回答
  •  暖寄归人
    2020-12-14 11:14

    I'm not sure, but are you the one that keeps down voting my answers/questions for no apparent reason (Or b/c of my views on VB.NET)?

    Anyway, PropertiesMustMatchAttribute is just a good implementation of using values of a specific property on an object. If you need to run some logic using multiple fields of an object you can do so with the following, similar to what PropertiesMustMatchAttribute does.

    Below would be the main part of a ValidationAttribute that accesses object properties to run some logic.

        public override bool IsValid(object value)
        {
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value);
    
            // Get the values of the properties we need. 
            // Alternatively, we don't need to hard code the property names,
            // and instead define them via the attribute constructor
            object prop1Value = properties.Find("Person", true).GetValue(value);
            object prop2Value = properties.Find("City", true).GetValue(value);
            object prop3Value = properties.Find("Country", true).GetValue(value);
    
            // We can cast the values we received to anything
            Person person = (Person)prop1value; 
            City city = (City)prop2value;
            Country country = (Country)prop3value;
    
            // Now we can manipulate the values, running any type of logic tests on them
            if(person.Name.Equals("Baddie") && city.ZIP == 123456)
            {
                return country.name.Equals("Australia");
            }
            else
            {
                return false;
            }         
        }
    

    PropertiesMustMatchAttribute is just using Reflection to accomplish a common task. I tried to break up the code to make it more readable/easier to understand.

提交回复
热议问题