ASP.NET Combine Validators and Client OnClick Events

 

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

 

 

(Visited 67 times, 2 visits today)

1 Comment

Your question, correction or clarification Ваш вопрос, поправка или уточнение

Editor on duty will review your comment. Can't wait? Discuss your topic right now in forums, if you register and login.     Required fields are marked with * Ваше послание пойдет на просмотр в редакцию. Не можете ждать? Обсудите ваш вопрос прямо сейчас в форуме Русский Круг , ecли вы зарегистрируетесь и войдёте под своим именем.     Поля, обязательные для заполнения, помечены *
* *