Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable validation in a 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 a 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 have found that I can disable client-side validation by setting class="cancel" on the "OK" button. This works fine.

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

Thank you for help!

like image 520
Slauma Avatar asked May 18 '11 17:05

Slauma


People also ask

How do you remove data annotation validation on client-side?

To disable client side validation, we need to disable it by force. Notice the @data_val= “false”. It will disable the validation on this field.

How to validate ModelState in MVC?

When MVC creates the model state for the submitted properties, it also iterates through each property in the view model and validates the property using attributes associated to it. If any errors are found, they are added to the Errors collection in the property's ModelState . Also note that ModelState.

Where can client-side validation be deactivated?

We can enable and disable the client-side validation by setting the values of ClientValidationEnabled & UnobtrusiveJavaScriptEnabled keys true or false. This setting will be applied to application level. For client-side validation, the values of above both the keys must be true.


1 Answers

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

ModelState.Remove("Propertyname");

To hide the errormessages you can use

ModelState.Clear();

But the question is why you submit the values if you do not use them? Would you not better use a reset button to reset the values in the form:

<input type="reset" value="Reset Form">
like image 100
slfan Avatar answered Oct 19 '22 22:10

slfan