Show ValidationSummary MVC3 as "alert-error" Bootstrap
Alternative solution. =)
@if (ViewData.ModelState.Any(x => x.Value.Errors.Any()))
{
// Bootstrap 2 = "alert-error", Bootstrap 3 and 4 = "alert-danger"
<div class="alert alert-danger alert-error">
<a class="close" data-dismiss="alert">×</a>
@Html.ValidationSummary(true, "Errors: ")
</div>
}
This answer is based on RickB's one
Updated for the latest bootstrap ==>>
doesn't exist in favor ofalert-error
alert-danger
.Works for all Validation Errors not only Key String.Empty ("")
For anyone using Bootstrap 3 and trying to get nice looking alerts:
if (ViewData.ModelState.Keys.Any(k=> ViewData.ModelState[k].Errors.Any())) {
<div class="alert alert-danger">
<button class="close" data-dismiss="alert" aria-hidden="true">×</button>
@Html.ValidationSummary(false, "Errors: ")
</div>
}
The solution provided by RickB works only on manually added errors on (String.Empty key) but not on those generated by ModelState (normally this gets triggered first via javascript but it's always a good practice to have a fallback if (for example) the Html.ValidationMessageFor
is missing or many other situations.
edited again
I misunderstood your question at first. I think the following is what you want:
@if (ViewData.ModelState[""] != null && ViewData.ModelState[""].Errors.Count > 0)
{
<div class="alert alert-error">
<button type="button" class="close" data-dismiss="alert">×</button>
@Html.ValidationSummary(true, "Errors: ")
</div>
}