ASP.NET/JavaScript - Why Isn't "Return False" Not Preventing Postback?

12,368

write return statement so when you click on button it return false which not allow to submit form

 <asp:Button ID="btnFoo" runat="server" Text="Foo" CssClass="button foo" 
OnClientClick="return foo_Click();" />
Share:
12,368

Related videos on Youtube

RPM1984
Author by

RPM1984

~ Past ~: Mainframes (Model 204, JCL) Java (J2SE, J2EE) Oracle VB.NET ASP.NET Web Forms/MVC ~ Present ~ .NET Core TDD, DDD (all the DDs!) Microservices Containers

Updated on April 29, 2022

Comments

  • RPM1984
    RPM1984 almost 2 years

    I feel like i've done this scenario plenty of times, and it usually works, so im obviously missing something.

    Here's my server-side ASP.NET Button:

    <asp:Button ID="btnFoo" runat="server" Text="Foo" CssClass="button foo" OnClientClick="foo_Click();" />
    

    Which get's rendered on the client as:

    <input type="submit" name="reallylongclientid" value="Foo" onclick="foo_Click();WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(reallylongclientidandpostbackoptions, false, false))" id="reallylongclientid" class="button foo">
    

    No surprises there.

    Here's the surprise, in my JavaScript function:

    function foo_Click() {
       return false;
    }
    

    Okay so there's more to it than that, but i cut it down to prove a point.

    When i click the button, it calls the client-side function, and returns false.

    But it still posts back to the server, why?

    I basically want to do this on the click of the button:

    1. Do client-side validation.
    2. If validation passes, post back
    3. If not, show some error messages on the form.

    Of course, i could change this to an client-side button (input type="button") and manually kick off the postback when i want, but i shouldn't need to do that. Or should i?

  • RPM1984
    RPM1984 over 13 years
    Knew it was obvious (slaps head). Thanks.
  • RPM1984
    RPM1984 over 13 years
    I just noticed that if i do "var passedValidation = new Boolean(false); return passedValidation" it still posts back. But if i just do return false, it doesnt. WTF? any ideas?
  • Christian C. Salvadó
    Christian C. Salvadó over 13 years
    @RPM1984: Using the Boolean constructor, with the new keyword, creates a Boolean object wrapper, and in JavaScript any object is considered to be truthy when used in boolean context, for example: !!new Boolean(false) ==> true, I would recommend you to simply use the boolean true or false literals, which represent directly primitive values...
  • RPM1984
    RPM1984 over 13 years
    @CMS - yep, i figured that. well that kinda sucks, oh well - ill stick to the basic. thanks for the clarification.