126

How do I access the ModelState from within my View (aspx page)?

Saajid Ismail
  • 8,029
  • 11
  • 48
  • 56
  • 1
    I don't think you should. That sort of thing should happen in the Controller. – Matthew Groves Jun 26 '09 at 13:38
  • 1
    I need to know if my ModelState is valid. I don't want to do this: <% if (Html.ValidationSummary() != null) %> <% { %>

    Your message was not sent. Please correct the errors below and try again.

    <% } %> Instead I want to do this: <% if (!ViewData.ModelState.IsValid) { %>

    Your message was not sent. Please correct the errors below and try again.

    <%} %>
    – Saajid Ismail Jun 26 '09 at 13:44
  • 12
    That sounds like a good enough reason to access ModelState – BritishDeveloper Jun 29 '11 at 08:29
  • There's absolutely nothing wrong with accessing ModelState in the view. It's part of ViewData. – kennythecoder Sep 12 '16 at 13:31

1 Answers1

195

Use ViewContext.ViewData.ModelState.

Abel
  • 56,041
  • 24
  • 146
  • 247
Mathias F
  • 15,906
  • 22
  • 89
  • 159
  • 22
    Also worthy to note that you can just do `ViewData.ModelState` and if you want to display some conditional markup on errors you can do like this: `@if (!ViewData.ModelState.IsValid)` – The Muffin Man Sep 15 '13 at 02:16