[SOLVED] Check condition before some postback

Issue

In my scenario i have many asp.net button in the page.
Each asp.net button when rendered on client side has a strucutre like the following :

<button onclick="__doPostBack('ctl00$...ID','')" type="button" class=".."></button>

Some of the button in the page have a special class that mean that the button will cause form validation :

<button onclick="__doPostBack('ctl00$...ID','')" type="button" class=".. require-validation"></button>

I would like to execute a javascript function for validate the form before run the regular onclick function only on those buttons. And if possibile i would like change this behaviour only in client side using jQuery (so that server side i have only to tag buttons with the appropiate class).

If i try to target (with jQuery) all the button with the class "require-validation" and attach the validation function (that will suppress the submit event) things works, but only sometimes.

Here the validation function example :

$("myOnlyPageForm").find(".require-validation").click(function (e) {
            if ( trikyValidationFail() )
                e.preventDefault();
        });

My understanding is that the button with "require-validation" has now two different event attached, so a click will fire them both and the order is not guaranteed. So sometimes it prevent the regular postback, but sometimes not (in my test always the first time the postback is prevented, but the second click cause a postback even if the validation always fail).

So till now i only can think to rewrite entirely the onclick code (using jQuery) so it will become :

<button onclick="trikyValidationFail() ?__doPostBack('ctl00$...ID','') : false" type="button" class=".. require-validation"></button>

but i am not sure if this is faseable, nor how to achieve that

Solution

Any plane jane asp.net button can have both a client side (JavaScript) click event, and then a server side event.

Hence, say we have a button, and want to confirm a delete operation.

  <asp:Button ID="cmdDelete" runat="server" Text="Server delete prompt" 
     OnClientClick="return confirm('Really delete this file?');"  />

so, if the ClientCick returns true, then server side buttion event will fire. If the ClientClick event returns false, then server side button event will NOT fire.

So, for each button, that function can simple return true, or false.

so, the button code server side can be this:

Protected Sub cmdDelete_Click1(sender As Object, e As EventArgs) Handles cmdDelete.Click

    Response.Write("<h2> This is the server side delete run code</h2>")
    ' real delete code follows

End Sub

So, the above will conditional run server side based on if client side routine returns true, or false.

Now, you have to be careful, since often these days a WHOLE LOT of JavaScript code routines run asynchronous. (js code don’t wait).

Say for example, I wanted to pop up a jQuery.UI dialog (in place of those HORRIBLE looking confirm’s ).

So, we might then call a jQuery.UI dialog, say like this:

        <asp:Button ID="cmdTest" runat="server" Text="Server Delete Prompt" ClientIDMode="Static"
            OnClientClick="return mytest2ok(this)"/>
        <br />

        <div id="MyDialog" style="display:none">
            <h2>my cool dialog text</h2>
            <h2>This delete operation can't be undone</h2>
        </div>

    <script>

        var mytest2ok = false
        function mytest(cmdBtn) {
            if (mytest2ok) {
                return true
            }

            myDialog = $("#MyDialog")
            myDialog.dialog({
                title: "Delete the whole server system",
                modal: true,
                appendTo: "form",
                autoOpen: false,
                buttons: {
                    ok: function () {
                        myDialog.dialog('close')
                        mytest2ok = true
                        $(cmdBtn).click()
                    },
                    cancel: function () {
                        myDialog.dialog('close')
                    }
                }
            })

            myDialog.dialog('open')
            return false
        }

    </script>

Now, when I click the button, I get this:

enter image description here

Now, in above, NOTE VERY close – when I click the server button, the client side code runs, displays the dialog, code falls through and returns false!!!!

Now, when I click ok, on the client side dialog, I then set my flag = true and CLICK THE BUTTON AGAIN (jquery.Click()). So now the buttion is clicked, the client side js runs again, returns true, and thus my server side button code then runs.

So, while it is 100% simple rule:

 If client click event returns true  - sever side code event runs
 if client click even returns false - server side code event does NOT run

The only real time you get in trouble, is for calling or using some js code that does not halt, and as a result, you can’t even using async (await), or even say a promise in js – it will STILl fall through. So in those cases, you either have the js code run, and then call a button or server side code, or in "many" cases, you can use the above true/false flag trick, and pass the button (this) to the js routine, and if it is to return true, set a flag, and click the button again in js, and the button click runs again, and with a true return value, server side code runs.

Answered By – Albert D. Kallal

Answer Checked By – David Goodson (BugsFixing Volunteer)

Leave a Reply

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