I am presented with a situation where I would like to use Html.ValidationSummary()
in my views to display a generic error message. Maybe something like "There was a problem with the information you entered."
but without getting a list of every single thing that went wrong (as per DataAnnotations).
side note: I've found references to people using if(ViewContext.ViewData.ModelState.IsValid){ ... }
in their views and foregoing ValidationSummary
altogether. I am not really impressed with that approach, to say the least.
It's important that the ModelStateDictionary
still contains a key for each model element which had a validation error (so that Html.EditorFor
, et al. write the correct css classes.)
What I ended up with and seems to work is:
public static class ModelStateHelpers
{
public static void Empty(this ModelStateDictionary @this)
{
foreach (KeyValuePair<string, ModelState> state in @this)
{
if (state.Value.Errors.Any())
{
state.Value.Errors.Clear();
state.Value.Errors.Add(String.Empty);
}
}
}
}
Followed by this in my class:
if (StuffWentWrong) {
this.ModelState.Empty();
this.ModelState.AddModelError("", "Something went wrong...");
}
As intended, the Html.ValidationSummary
is smart enough to suppress html structure for ModelStates
in the dictionary whose error messages are blank; and I also end up with text fields decorated with error validation attributes, such as <input class="input-validation-error text-box single-line" data-val="true" data-val-required="The User Name field is required." id="UserName" name="UserName" type="text" value="" />
Does this particular solution smell badly?