ASP.NET Combine Validators and Client OnClick Events

2017/05/03
By
Modified: 2017/04/30

 

Imagine you need to use control validators, and you also need to attach  additional logic to OnClick event.

These two will fight with each other, if you use conventional interface features.

If you add OnClick attribute too early (say in GridView_RowEditing event)  it will be overwritten by Validators.  If you add OnClick  attribute very late (say in  Render event) Validators logic will be lost.

To make this work, you need to  use a special JavaScript function that combines both procedures.

Here is how you do it:

You need to change  a few things on the button that causes validation:

                      <asp:ImageButton ID="imgUpdate" runat="server" CausesValidation="false"
                        OnClientClick="return isValid(this);" ImageUrl="~/Images/Update32x32.png"
                        Text="Update" ValidationGroup="CategoryUpdate" ToolTip="Update"
                        OnClick="imgUpdate_Click" />

Main thing to notice here is  CausesValidation=”false”.  You will call the validation function on your own.  You are calling your custom function ( … OnClientClick=”return isValid(this); … )   that will combine validators and your custom code.

 

The JavaScript script will look like this:

    <script type="text/javascript">
        function isValid(obj) {
            // First check page validators
            Page_ClientValidate();
            if (!Page_IsValid) return false;
            // 2015-08-25 TU  21:09  Get old and new task categories
            var _pos1 = obj.id.lastIndexOf('_') + 1;
            var _prefix = obj.id.substring(0, _pos1);
            var oldCategory = document.getElementById(_prefix + 'txtOldCategory');
            var newCategory = document.getElementById(_prefix + 'txtTaskCategory');
            // Next, dispaly a confirmation box
            return confirm("Old task category   " + oldCategory.value +
                "   will be renamed to \n  a new task category   " + newCategory.value +
                "   for all related tasks! \n Are you sure?");
        }
    </script>

Let’s examine the script.   You do not need to write the function Page_ClientValidate() .  You just call it.  If all the validators are OK, variable Page_IsValid will be true.  In that case function will continue to execute  your additional custom logic – in this case a confirmation box.

Sources:

Simple, elegant and inspired by a support exchange on ASP.NET:

http://forums.asp.net/t/1711290.aspx/1?Validators+and+Custom+OnClick+Javascript

 

 

Tags: , , , ,


One Response to ASP.NET Combine Validators and Client OnClick Events

  1. Bmju
    2015/11/16 at 11:28

    That is very useful. Thank you.

Add Your Comment Ваш Комментарий

Your email address will not be published. Required fields are marked *

* Ваше Имя *
* Ваш Email (не будет показан на сайте)*

*