Julian Dormon
Julian Dormon

Reputation: 1779

MVC 5 Html.ValidationSummary is not showing error

I am manually adding the following Model Error in my controller,

ModelState.AddModelError(string.Empty, "An error occurred");

However when the view is loaded, the @Html.ValidationSummary(true) is not showing any errors.

I have also tried @Html.ValidationSummary(false).

I have read many articles on this behavior and I have tried all the suggestions with no luck.

Any suggestions are greatly appreciated!

Upvotes: 3

Views: 11935

Answers (2)

barrypicker
barrypicker

Reputation: 10088

Beware when using custom ViewData objects.

Problem Reproduced

Model

using System.ComponentModel.DataAnnotations;

namespace BrokenValidationSummaryTest.Models
{
    public class MyModel
    {
        [Required]
        public string Whatever { get; set; }
    }
}

Controller

using BrokenValidationSummaryTest.Models;
using System.Web.Mvc;

namespace BrokenValidationSummaryTest.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Submit(MyModel postedData)
        {
            return View(viewName: "Index", model: postedData);
        }
    }
}

View "Index"

@model BrokenValidationSummaryTest.Models.MyModel

<ul class="nav nav-tabs" id="carrier-tabs">
    <li class="active">
        <a data-toggle="tab" href="#search" class="tab-level-1" data-tab-name="search">Search</a>
    </li>
</ul>

<div class="tab-content">
    <div id="search" class="tab-pane fade in active">
        @Html.Partial(partialViewName: "TabBody", model: Model, viewData: new ViewDataDictionary())
    </div>
</div>

View "TabBody"

@model BrokenValidationSummaryTest.Models.MyModel

@Html.ValidationSummary(excludePropertyErrors: false)

<h2>TabBody</h2>

    @using (Html.BeginForm(actionName: "Submit", controllerName: "Home", method: FormMethod.Post))
    {
        <div>Whatever:</div>
        <div>@Html.TextBoxFor(x=>x.Whatever)</div>

        <input type="submit" value="Submit">
    }

Explanation

The partial view has the ValidationSummary HTML helper. We pass a custom ViewData object to the partial view. This custom ViewData object passed to the partial view does not contain the ViewState found in the view 'Index'. The HTML helper ValidationSummary does not have enough required information to render the error messages properly.

Recommendation: if using custom ViewData, populate the custom ViewData with the ViewState of the parent view.

Upvotes: 0

lbrahim
lbrahim

Reputation: 3810

I can see it work. See the sample here: http://dotnetfiddle.net/Jz7wQj

Upvotes: 2

Related Questions