How can I check if Html.ValidationSummary() has any errors?
Ultimate result required:
<% if(I_HAVE_ERRORS) {%>
<div><%= Html.ValidationSummary() %></div>
<%}%>
In other words, how can I determin开发者_高级运维e "I_HAVE_ERRORS"?
<%if (!Html.ViewData.ModelState.IsValid){%>
To use with razor
syntax
@if (!Html.ViewData.ModelState.IsValid)
{
// show error
}
or you can wrap it up as an extension method
public static bool HasErrors(this HtmlHelper helper)
{
return helper.ViewData.ModelState.IsValid == false;
}
Use it as
@if (Html.HasError())
{
// show error
}
If you need to check for errors not related to any specific fields, you could try this:
@if(Html.ViewData.ModelState.ContainsKey(string.Empty))
{
<div class="panel panel-danger">
<div class="panel-heading">
@Html.ValidationSummary(true)
</div>
</div>
}
Actually, I think the most correct way of checking for validation errors (not just auto generated ones based on the model), would be;
@if (Model.ViewData.ModelState.ErrorCount > 0)
{
}
This way it will include user generated model errors.
精彩评论