Consider this model class:
public class FooModel {
public Person Manager { get; set; }
public Person Employee { get; set; }
}
public class Person {
[Required]
public String Name { get; set; }
}
If the user provides a Name value in a form for the Manager but not the Employee then the ValidationSummary() will return the message “Name is required” without qualifying it further (i.e. it isn’t clear that Employee.Name isn’t set but Manager.Name is).
What solutions are there to this problem?
The question here: ( How do I show a different Required message to instances of the same object in MVC3? ) has two answers.
The first suggests flattening the ViewModel, in my case that would mean copying the
Personmembers intoFooModeltwice, then I could set a customized validation message for both. I decided against this for obvious reasons (myPersonclass is considerably more complicated and also used elsewhere).The second answer suggests modifying ModelState’s error messages, which is what I do. I’ve already developed a way for ViewModels to modify their own validation so adding this trick was easy enough. I’ve added a [DisplayName] attribute like so (psuedocode):
if( modelState.IsInvalidByPrefix(“Employee”) ) {
modelState.AppendErrorMessageDisplayPrefix( GetLocalisedDisplayName(“Employee”) );
}
}
}