2

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.

WhiteWade
  • 35
  • 7

1 Answers1

1

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;
}
Raphaël Althaus
  • 59,727
  • 6
  • 96
  • 122
  • Correct me if I'm wrong but to only show model errors the parameter should be set to true. I've edited the original post to try to clarify what I'm trying to achieve. – WhiteWade Jul 12 '12 at 12:28
  • @WhiteWade oh oh oh, you're right, sorry. Well, edited, but it doesn't help you. I'll try to find a better way. – Raphaël Althaus Jul 12 '12 at 12:39
  • Thank you for your help. Almost perfect. Just had to change `this HtmlHelper helper` to `this HtmlHelper htmlHelper` – WhiteWade Jul 12 '12 at 13:56