Question

I've done some searching on Google and Stack Overflow but can't find the answer to this one.

I have the following in my view

@if (!Html.ViewData.ModelState.IsValid)
{
    @Html.ValidationSummary(true)<br />
}

I'm only interested in model errors but the test will return true if property errors are found. How do I test just model errors?

I may need to clarify here, I want to do the test to stop the <br /> being written out when there is a property error but no model error.

Was it helpful?

Solution

if you go to the source of ValidationSummary, you can find

IEnumerable<ModelState> modelStates = null;
if (excludePropertyErrors) { 
    ModelState ms;
    htmlHelper.ViewData.ModelState.TryGetValue(htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix, out ms);
    if (ms != null) {
        modelStates = new ModelState[] { ms }; 
    }
} 
else { 
    modelStates = htmlHelper.ViewData.ModelState.Values;
} 

So I think you could make a method like that

public static bool ModelStateHasModelErrors(this HtmlHelper htmlHelper) {
   ModelState ms;
   htmlHelper.ViewData.ModelState.TryGetValue(htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix, out ms);
   return ms != null;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top