I’m having some troubles with ASP MVC error handling.
On a form that a user tries to connect to a device. If the uses input an invalid device name, it’s pretty straightforward to tell the user the name is invalid.
I’m implementing IEnumerable<RuleViolation> GetRulesViolations() on all my data classes. The RuleViolation class has two fields: PropertyName and ErrorMessage and if I get an error on submit I just call the GetRulesViolations method and set the errors on the ModelState:
catch {
foreach (var issue in device.GetRulesViolations()) {
ModelState.AddModelError(issue.PropertyName, issue.ErrorMessage);
}
return View();
}
and with some background asp mvc magic the error appears on the view in the ValidationMessage placeholder for the model.Name:
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<p>
<input type="submit" value="Connect" />
</p>
</fieldset>
}
Now the problem:
If the error i’m getting is something like “Could not connect to the device” that’s not a problem related to the Name field. It’s a message that should appear above the form because it’s related to the whole form.
Is there a straightforward way to set this like ModelState.AddError(“error message”) without telling the key so it would apply to the whole form or should I create an Error hidden property on the Data classes and place a validation message for that property above the form?
Yes, empty field name, like this :