This tip comes to you from my blog, but the hat-tip goes to Andres Nelson whom I work with at my current client who actually showed me how to do this.
The Scenario
You have a grid with multiple fields. These fields are dependent upon each other. If one field is empty, then the other field is empty. At that point you want to display ONE error message informing the user that something is wrong, but you want to highlight both fields, as shown below in Figure 1-1. Please excuse the blurring of everything, but its NDA, you know how it goes. 🙂 Click for a larger view.
Figure 1-1: Highlighting both fields, but providing one error message.
Solution
I never thought of this, but its actually pretty simple, so again – hat tip to Andres. Simply add two ModelState errors, one for each property you want highlighted. However, for the second field, provide and empty string. MVC will not show that error in the validation summary, but the field will still get highlighted. Here’s the code –
bindingContext.ModelState.AddModelError("Field1Name", "Hey! Bad Stuffs Happens!"); // The one below will not show up in the validation summary, but the field will be highlighted. bindingContext.ModelState.AddModelError("Field2Name", String.Empty);
That’s it!