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

12,720

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

Solution 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.

Solution 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.

Solution 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...

Share:
12,720
Slauma
Author by

Slauma

Updated on June 26, 2022

Comments

  • Slauma
    Slauma about 2 years

    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!

  • Slauma
    Slauma about 13 years
    It's the same strongly-typed view, so I think I cannot use another ViewModel.
  • chobo2
    chobo2 about 13 years
    I just wrote that you should try that. I don't think it will have really any downside if you are sure you don't want to display those errors. I am unsure why you don't want to display the errors if they click the submit button and nothing has been entered in.
  • Chris Marisic
    Chris Marisic about 13 years
    @Slauma that's not the entire case. You have an individual view, that uses Model X that probably has all of your validation attributes. You could create Model Y that you copy and paste Model X into and remove all the validation attributes. At this point you need to have 2 separate form post actions. So Create(X) and TempSave(Y). At the end of TempSave(Y) you would either want to redirect to the original action (if it can load the temp save data) or you would need to return View(X) which you can easily get Y to be an X by using mapping frameworks like ValueInjecter.
  • Chris Marisic
    Chris Marisic about 13 years
    You could then bind javascript to the submit button that would change target of the form from being TempSave to Create.
  • Chris Marisic
    Chris Marisic about 13 years
    it still is going ahead and check your validation and showing up on the client side I don't believe that's the case as the OP said on their OK button they have the cancel class which I am assuming unobtrusively makes that bypass the validation for client side.
  • Chris Marisic
    Chris Marisic about 13 years
    @Leons the validation COULD be in their model class, it doesn't have to be. If you're using a custom validation factory you can have your validation code anywhere. I use FluentValidation's replacement for the MVC validator, so I have all my validation in separate ruleset files.
  • Slauma
    Slauma about 13 years
    @chobo2: Lol, yes, now there are a lot of answers suggesting to clear the ModelState, so I feel safe that it's not completely wrong. There is a difference between "OK" and "Save" button. Only the "Save" button writes to DB and therefore needs validation. The "OK" button doesn't write to DB. It only fetches some additional data into the ViewModel and redisplays the view. I don't want validation at this point. It's kind of a dependent dropdown list logic: Select entry in first dropdown, click "OK", fill second dropdown list depending on the selection in first dropdown.
  • chobo2
    chobo2 about 13 years
    @Chris Marisic - I believe the client side validation is disabled(otherwise the form would not summit) but he has a Html.ValidationSummary() that takes all the errors from the server side and put's it on the page. It eventually shows up on the client side. Thats what I meant by it being on the client side.
  • chobo2
    chobo2 about 13 years
    Ah I thought you just did not want to show validation to people who clicked blank forms. I don't see anything wrong with using it as long you are sure that any bad data won't somehow get somewhere else(ie like saving it blindly in a database what you seem to not be doing).
  • Slauma
    Slauma about 13 years
    @Chris Marisic: I see, thanks for explanation! But it is somehow like cracking a nut with a sledgehammer. The ModelState.Clear() option seems to work fine. The background is a "Dependent DropDown-Lists scenario" without JS/Ajax (see my comment to my own answer).
  • Leons
    Leons about 13 years
    @Chris Marisic - Very good point, I assumed it has to be there, but it could be in client side. I will check out FluentValidation for future projects.