Reputation: 2914
Currently, I'm setting ViewBag.HasError
in my controller, then using that variable in my view to determine if the html providing the validation message should be written to screen.
start.cshtml:
@if (ViewBag.HasError != null && ViewBag.HasError)
{
<tr>
<td colspan="2">
@Html.ValidationMessageFor(m => m.Email)<br />
</td>
</tr>
}
is there something similar within the framework already?
Upvotes: 0
Views: 151
Reputation: 56716
You do not need any flags for this, framework already has everything in place. When it comes to ValidationMessageFor
execution, ModelState
is checked to contain this specific message. If the message is found (meaning that the validation was done), it is displayed, otherwise this methods adds nothing to the output.
However there are some built-in features that allow you to check model state on the view. Here is how to check is the model is valid in general (similar to what you have implemented):
@ViewData.ModelState.IsValid
And here is how to check errors for specific field:
@ViewData.ModelState["Email"].Errors.Count != 0
Upvotes: 1