1110
1110

Reputation: 6829

How to remove list from validation summary

I added ValidationSummary Html helper for my View Model class which has 5 required fields. And it works got nice red words missing 1, missing 2 etc. But I need to display just one message not five of them (something like: "Your input is not valid."). Can this be done with ValidationSummary?

Upvotes: 14

Views: 13840

Answers (4)

xr280xr
xr280xr

Reputation: 13302

One brute force approach I've used in MVC3:

if (!ModelState.IsValid)
{
    ModelState.AddModelError("", "Some contextual error message");
}

and display it on your page:

<% if(!ViewData.ModelState.IsValid) { %>
    <span class="error"><%=ViewData.ModelState[String.Empty].Errors[0].ErrorMessage %> </span>
<% } %>

Upvotes: 0

pauloya
pauloya

Reputation: 2563

If you look at MVC3 source code you'll see that, currently, if you use ValidationSummary with excludePropertyErrors=true while having UnobtrusiveJavaScriptEnabled, there won't be any validation summary rendered.

I was able to display just a single message with MVC3 with UnobtrusiveJavascript enabled, for client side validation. Don't use @Html.ValidationSummary at all, and render:

@{
    //Show the message when there are server side errors
    ViewBag.ValidationSummaryClass = ViewData.ModelState.IsValid ? "validation-summary-valid" : "validation-summary-errors";
}
<div class="@ViewBag.ValidationSummaryClass" data-valmsg-summary="true">
    <span>Before you can continue, please make sure you have completed the mandatory fields highlighted above.</span>
    <ul style="display:none"/>
</div>

Notice the display:none, unobtrusive javascript still fills the list with error messages, but they are kept hidden.

Upvotes: 2

Amadiere
Amadiere

Reputation: 11416

You can try skipping the helpers if all you want to do is simply display a message if the ModelState is not valid. Simply check the ModelState within ViewData and that should work.

@if (!ViewData.ModelState.IsValid)
{
    <p>Your input is not valid.</p>
}

Upvotes: 4

Rune
Rune

Reputation: 8380

You have two options (at least):

Either use the validation summary and exclude property errors:

@Html.ValidationSummary(true, "The input is not valid")

or associate a error message with a custom key in your action:

if (!ModelState.IsValid)
{
    ModelState.AddModelError("myerrorsummary", "The input is not valid");
}

and display it on your page:

@Html.ValidationMessage("myerrorsummary")

Upvotes: 16

Related Questions