I am having a slight issue with the use of ValidationSummary(true)
to display model level errors. If the ModelState does not contain model errors (i.e. ModelState.AddModelError("", "Error Description")
) but contains property errors (added using data annotations) it displays the validation summary with no error information (when you view the source). My css is therefore displaying an empty red box like so:
If there are no property errors then no validation summary is displayed. With ValidationSummary(true)
I would expect it to only display validation errors if there are model errors. What have I misunderstood?
I have a basic project as follows:
Controller:
public class HomeController : Controller
{
public ViewResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(IndexViewModel model)
{
return View();
}
}
Model:
public class IndexViewModel
{
[Required]
public string Name { get; set; }
}
View:
@model IndexViewModel
@Html.ValidationSummary(true)
@using(@Html.BeginForm())
{
@Html.TextBoxFor(m => m.Name)
<input type="submit" value="submit" />
}
@if (ViewContext.ViewData.ModelState.Where(x => x.Key == "").Any())
{
@Html.ValidationSummary(true, null, new { @class = "ui-state-error" })
}
This checks if there are any model wide errors and only renders the summary when there are some.
I think there is something wrong with the ValidationSummary
helper method. You could easily create a custom helper method that wraps the built-in ValidationSummary
.
public static MvcHtmlString CustomValidationSummary(this HtmlHelper htmlHelper, bool excludePropertyErrors)
{
var htmlString = htmlHelper.ValidationSummary(excludePropertyErrors);
if (htmlString != null)
{
XElement xEl = XElement.Parse(htmlString.ToHtmlString());
var lis = xEl.Element("ul").Elements("li");
if (lis.Count() == 1 && lis.First().Value == "")
return null;
}
return htmlString;
}
Then from your view,
@Html.CustomValidationSummary(true)
Check this question too.
You could hide the summary with CSS:
.validation-summary-valid { display:none; }
Also, you could put the validation summary before the Html.BeginForm()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With