Note that there are some explanatory texts on larger screens.

plurals
  1. POCan ASP.Net MVC 2 Custom attributes on class level and on property level be active in the same time?
    text
    copied!<p>I am working on asp.net mvc 2 web application. I have model with 3 properties:</p> <pre><code>[IsCityInCountry("CountryID", "CityID"] public class UserInfo { [Required] public int UserID { get; set; } [Required] public int CountryID { get; set; } [Required] public int CityID { get; set; } } </code></pre> <p>I have one "required" property attribute, and one attribute on class level :</p> <pre><code>using System; using System.ComponentModel; using System.ComponentModel.DataAnnotations; [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)] public class IsCityInCountry : ValidationAttribute { public IsCityInCountry(string countryIDProperty, string cityIDProperty) { CountryIDProperty = countryIDProperty; CityIDProperty = cityIDProperty; } public string CountryIDProperty { get; set; } public string CityIDProperty { get; set; } public override bool IsValid(object value) { var properties = TypeDescriptor.GetProperties(value); var countryID = properties.Find(CountryIDProperty, true).GetValue(value); var cityID = properties.Find(CityIDProperty , true).GetValue(value); int countryIDInt; int.TryParse(countryID.ToString(), out countryIDInt); int cityIDInt; int.TryParse(cityID.ToString(), out cityIDInt); if (CountryBusiness.IsCityInCountry(countryIDInt, cityIDInt)) { return true; } return false; } } </code></pre> <p>When I post the form on my view, and CountryID is not entered, in ModelState dictionary there's an error about that issue. Other attribute is ignored ("IsCityInCountry"). When I choose CountryID and CityID, which is not in selected country, I get appropriate validation message about that, and ModelState has another key (which is ""). I understand that advantage have property attributes and then class attributes. My question; is there any way to get all validation messages at the same time, no matter what kind of attributes are involved (class or property attributes)? Thanks in advance.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload