如何在ASP.NET MVC 2中执行“causevalidation = false”?

时间:2022-12-02 04:14:16

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:

我在服务器上使用Data Annotations进行验证,例如:

    [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(); %>

1 个解决方案

#1


5  

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.

如果触发按钮有一个名为“disableValidation”的字段,其值为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:

在服务器端,你的问题有点难以回答,因为这完全取决于你是否以及如何进行模型绑定以及当有人点击该搜索按钮时你的控制器方法会做什么。一个选项可能只是清除ModelState中的所有错误......这是一个方法:

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.

如果您从控制器发布一些示例代码,我可以尝试给出更好的答案。

#1


5  

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.

如果触发按钮有一个名为“disableValidation”的字段,其值为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:

在服务器端,你的问题有点难以回答,因为这完全取决于你是否以及如何进行模型绑定以及当有人点击该搜索按钮时你的控制器方法会做什么。一个选项可能只是清除ModelState中的所有错误......这是一个方法:

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.

如果您从控制器发布一些示例代码,我可以尝试给出更好的答案。