Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I do "causesvalidation=false" in ASP.NET MVC 2?

I have two buttons on a single form. One is used to submit the form while the other is used to search. I do not want the search button to trigger any server side or client side validation.

How can I do this?

Thanks.

Edit

I'm using Data Annotations on the server to validate, example:

    [Required(ErrorMessage = "Institution is required")]
    [Range(1, 2, ErrorMessage="Please select an institution")]
    [DisplayName("Institution")]
    public int InstitutionId { get; set; }

And on the client I'm using this:

<% Html.EnableClientValidation(); %>
like image 762
Mike Avatar asked Aug 12 '10 17:08

Mike


1 Answers

To disable the client-side validation for your search button, add a script like this to your page:

<script type="text/javascript">
  document.getElementById("searchButton").disableValidation = true;
</script>

The client side validation won't run if the triggering button has a field called "disableValidation" that evaluates to true.

On the server side, your question is a bit tougher to answer because it all depends on if and how you are doing model binding and what your controller method does when someone clicks that search button. One option might be just to clear out all the errors from ModelState ... here's a method to do that:

private static void ClearErrors(ModelStateDictionary modelState)
{
    foreach (var key in modelState.Keys)
    {
        modelState[key].Errors.Clear();
    }
}

If you post some sample code from your controller, I can try to give a better answer.

like image 50
Peter Avatar answered Nov 14 '22 13:11

Peter