How to disable validation in a HttpPost action in

2019-04-28 09:08发布

问题:

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!

回答1:

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">


回答2:

So if there is nothing in your submit string you want it to ignore checking if the model state is valid and assume that it is.

However it still is going ahead and check your validation and showing up on the client side through the validation summary.

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

ModelState.Clear()

and remove all the errors out of it.



回答3:

The server-side validation must be in your MyViewModel class. Can you use a different class that does not implement the validation? The data annotations in the ViewModel is responsible for setting ModelState.IsValid to false.



回答4:

Now, I just had this idea:

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

Indeed I don't get messages in ValidationSummary anymore. Does this have any downside or undesirable side effect? At least I cannot see an issue at the moment...