Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Data annotations can be used to validate models on both the client <em>and</em> the server. </p> <p>On the server-side the <code>DefaultModelBinder</code> will automatically validate the models that are POSTed to your action methods but it won't prevent invalid models from being POSTed. It will simply add the error to the <code>ModelState</code> and set the <code>ModelState.IsValid</code> property to <code>false</code> (as you have discovered). That means you need to check the <code>ModelState.IsValid</code> property and redisplay the form with the model if it isn't valid:</p> <pre><code>[HttpPost] public ActionResult Edit(MyViewModel model, string button) { if (!ModelState.IsValid) { // The model isn't valid. // Redisplay the form with the invalid model. return View(model); } // If we got here it means the model is valid. } </code></pre> <p>Redisplaying the form with the invalid model will allow any <code>@Html.ValidationSummary()</code> or <code>@Html.ValidationMessageFor(m =&gt; m.UserName)</code> helper methods to render their validation error messages to the page.</p> <blockquote> <p>As far as I know, my action should not be called if the model validation fails.</p> </blockquote> <p>This is only true if client-side validation is enabled. You can do this by adding the following <em>appSettings</em> to your Web.config file:</p> <pre><code>&lt;appSettings&gt; &lt;add key="ClientValidationEnabled" value="true" /&gt; &lt;add key="UnobtrusiveJavaScriptEnabled" value="true" /&gt; &lt;/appSettings&gt; </code></pre> <p>... and adding references to the <em>jquery.validate.js</em> and <em>jquery.validate.unobtrusive.js</em> scripts to your view. This will allow JavaScript to validate the model <em>before</em> it is sent to the server and the validation messages will show without a page refresh (much better for the user and your server!). As @John H pointed out in the question comments, client-side validation is no substitute for server-side validation. So be sure to leave your server-side validation checks in place.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload