views:

1189

answers:

2

I have a usercontrol in ASP.Net featuring a button that I use to postback. This button also has some Javascript validation that is done before it processes the event.

Today I tried to postback to another URL by setting the PostBackURL property of the button. But it didn't work and the page kept posting back to itself. So I did some investigation and found that.

  1. Post back to another URL is implemented through Javascript in ASP.Net.
  2. If I keep the call to my validation function

    OnClientClick="return validate()" Then the post back does not occur.

  3. If I remove the call to the validation function, the postback works fine.

This is how the button markup looks with Validation on.

<input type="submit" name="ctl00$cphMain$pra1$btnSubmit" value="Submit" onclick="return validate();WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;ctl00$cphMain$pra1$btnSubmit&quot;, &quot;&quot;, false, &quot;&quot;, &quot;Result.aspx&quot;, false, false))" id="ctl00_cphMain_pra1_btnSubmit" style="width:80px;" />

Without validation

<input type="submit" name="ctl00$cphMain$pra1$btnSubmit" value="Submit" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;ctl00$cphMain$pra1$btnSubmit&quot;, &quot;&quot;, false, &quot;&quot;, &quot;Result.aspx&quot;, false, false))" id="ctl00_cphMain_pra1_btnSubmit" style="width:80px;" />

You'll notice that the call to 'return validate()' is missing, and that is making all the difference.

How can I get this to work?

+1  A: 

its because the return prevents WebForm_DoPostBackWithOptions from executing, regardless of the result of the validation.

you could try (without quotes):

"!validate() ? return false : "

that way it would end up as:

!validate() ? return false : WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;ctl00$cphMain$pra1$btnSubmit&quot;, &quot;&quot;, false, &quot;&quot;, &quot;Result.aspx&quot;, false, false))

a crude hack, but thats webforms for you, one big hack on top of another.

Andrew Bullock
I'd prefer javascript code that would work standalone. A little bit less of a hack since it doesn't rely on any assumptions about how it's used.
tvanfosson
Right! Thanks for the solution.
Cyril Gupta
+5  A: 

Replace

OnClientClick="return validate();"

with

OnClientClick="if (!validate()) { return false; }"
tvanfosson
Thanks tvanfosson!
Cyril Gupta
agreed, this is a neater solution.
Andrew Bullock