How to disable validation in HttpPost action in ASP.NET MVC 3?

I have a create-view like this ...

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script> @using (Html.BeginForm()) { @Html.ValidationSummary(null, new { @class = "validation" }) ... <input class="cancel" type="submit" value="OK" /> ... <input name="submit" type="submit" value="Save" /> } 

... and the corresponding controller action:

 [HttpPost] public ActionResult Create(string submit, MyViewModel myViewModel) { if (submit != null) // true, if "Save" button has been clicked { if (ModelState.IsValid) { // save model data return RedirectToAction("Index"); } } else // if "OK" button has been clicked { // Disable somehow validation here so that // no validation errors are displayed in ValidationSummary } // prepare some data in myViewModel ... return View(myViewModel); // ... and display page again } 

I found that I can turn off client-side validation by setting class="cancel" to the "OK" button. It works great.

However, server-side validation is still in progress. Is there a way to disable it in the controller action (see Else-block in the Create action above)?

Thank you for your help!

+6
source share
4 answers

I recently had a similar problem. I wanted to exclude some properties from checking and used the following code:

 ModelState.Remove("Propertyname"); 

To hide errors you can use

 ModelState.Clear(); 

But the question is, why are you sending values ​​if you are not using them? Isn't it better to use the reset button to reset the value in the form:

 <input type="reset" value="Reset Form"> 
+7
source

So, if there is nothing in your send line, you want it to ignore checking the correct state of the model and assume that it is.

However, it still goes ahead and validates your verification and is displayed on the client side through the verification summary.

If you really don't care about errors in this case, try

 ModelState.Clear() 

and remove all errors from it.

+4
source

Server-side validation should be in your MyViewModel class. Can you use another class that does not validate? Data annotations in ViewModel are responsible for setting ModelState.IsValid to false.

+2
source

Now I had this idea:

 ... else // if "OK" button has been clicked { ModelState.Clear(); } ... 

Indeed, I no longer receive messages in ValidationSummary. Does this have a flaw or an undesirable side effect? At least I don't see a problem at the moment ...

+1
source

Source: https://habr.com/ru/post/888452/


All Articles