Search code examples
asp.net-mvcvalidationerror-handlingmodelstate

How to check if ModelState contains errors which are not properties


In View i have following error helper

@Html.ValidationSummary(true)

Which, if some property is not validated, show following html

<div class="validation-summary-errors">
<ul>
<li style="display:none"></li>
</ul>
</div>

I have custom css for this class with red border background and problem is that even no error text is shown to user, red border is still displayed.

Can i somehow prevent showing following error html ? Like

@if (Html.ModelState.ContainsNonPropertyErrors() == true)
{
Html.ValidationSummary(true)
}

// or to check if ModelState Error array contains empty keys, becase these are custom messages.

also, can i somehow check if form was submitted to display successfull message ?

for example

@if (Html.ModelState.FormWasSubmitted() == true)
    {
    if (Html.ModelState.ContainsNonPropertyErrors() == true)
    {
    Html.ValidationSummary(true)
    } else {
    Html.Raw("Operation was successfull.")
    }
}

or it is a good practice to have model.successfullMessage property in the ViewModel ? (and in view something like @if(ModelState.IsValid) {@Model.successfullMessage} )

How do you do it ?


Solution

  • Ok i think i have working solution

    @if (ViewData.ModelState.Keys.Contains(string.Empty))
    {
         @Html.ValidationSummary(true)
    }