views:

6

answers:

1

There are no errors with my Javascript. The Javascript returns false, and the form is submitted. Additionally when setting UseSubmitBehavior to false the form still submits. What am I missing to prevent the form from being submitted?

// DerivedButton.cs
public class DerivedButton : System.Web.UI.WebControls.Button
{
  public DerivedButton2()
    : base()
  {
    this.OnClientClick = "DerivedButton_OnClick()";
    //this.UseSubmitBehavior = false;
  }

  protected override void OnPreRender(EventArgs e)
  {
    base.OnPreRender(e);
    string resourceName = "MyControls.DerivedButton.js";

    ClientScriptManager scriptManager = this.Page.ClientScript;
    scriptManager.RegisterClientScriptResource(
      typeof(MyControls.DerivedButton), 
      resourceName);
  }
}


//DerivedButton.js
function DerivedButton_OnClick()
{
  var answer = confirm("Are you sure?");
  return answer;
}

//Output Html
<input type="submit" 
       name="DerivedButton1" 
       value="SomeButton" 
       onclick="DerivedButton_OnClick();
         WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions                     
           (&quot;DerivedButton1&quot;, &quot;&quot;, false, &quot;&quot;,
            &quot;Default2.aspx&quot;, false, false))"
       id="DerivedButton1" />
+1  A: 

Try changing your OnClientClick to something like this:

this.OnClientClick = "if (!DerivedButton_OnClick()) return false";

This should work, although I suspect there's probably a more elegant way to do what you want.

LukeH
Ahh I see whats happening, I'm not returning the value of my function! Your code works but it can be shortened.
Erik Philips
@Erik: Out of curiosity, how can it be shortened? If you just do `return DerivedButton_OnClick()` then it'll always short-circuit, which means that all the `WebForm_DoPostBackWithOptions(...)` stuff will be skipped even when your method returns true.
LukeH
You're right, the shortened version does exactly what you said. Now I have determined I shouldn't be programming at this hour.
Erik Philips