开发者

Check if Html.ValidationSummary() has a value

开发者 https://www.devze.com 2023-01-23 21:21 出处:网络
How can I check if Html.ValidationSummary() has any errors? Ultimate result required: <% if(I_HAVE_ERRORS) {%>

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消