I want to show a ValidationSummary mcv3 with \"alert-error\" Bootstrap styling.
I\'m using a Razor view, and I show model errors with this code:
@Html.V
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>
}
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>
}
I did not like how the ValidationSummary rendered using a bullet list (unordered list). It had a lot of unnecessary space below the error list.
A solution to that issue - is simply to loop through the errors and render the errors how you want. I used paragraphs. For example:
@if (ViewData.ModelState.Any(x => x.Value.Errors.Any()))
{
<div class="alert alert-danger" role="alert">
<a class="close" data-dismiss="alert">×</a>
@foreach (var modelError in Html.ViewData.ModelState.SelectMany(keyValuePair => keyValuePair.Value.Errors))
{
<p>@modelError.ErrorMessage</p>
}
</div>
}
The result, in my case, looks something like this:
Consider writing an extension method to the HtmlHelper like:
public static class HtmlHelperExtensions
{
public static HtmlString ValidationSummaryBootstrap(this HtmlHelper htmlHelper)
{
if (htmlHelper == null)
{
throw new ArgumentNullException("htmlHelper");
}
if (htmlHelper.ViewData.ModelState.IsValid)
{
return new HtmlString(string.Empty);
}
return new HtmlString(
"<div class=\"alert alert-warning\">"
+ htmlHelper.ValidationSummary()
+ "</div>");
}
}
Then you just need to fit the ul-li styling in your stylesheet.