Showing posts with label form. Show all posts
Showing posts with label form. Show all posts

Monday, September 7, 2009

"Enter" submits my ASP.NET form!

ASP.NET encourages web pages to be written as one big <form>, and every interaction with it to be a POST to the server ("Postback" in ASP.NET). This means pages often have multiple auto-generated <input type="submit"> elements.

On some browsers, pressing Enter causes the first submit button to be "clicked". In pages with many such buttons, that's usually not what you want. As a hack to make "Enter" do nothing on an already-built page, I added the following before any other submit button:

<div style="visibility:hidden;height:0;">
  <input type="submit" value="Dummy" onclick="return false;" />
</div>

Now this do-nothing, invisible submit button "catches" the Enter and prevents the next button from being "clicked". This requires JavaScript turned on, but ASP.NET's "Postbacks" require them anyway, so no big loss.

Implementation note: using 'display:none;' caused the browser to ignore it, so I had to resort to 'visibility:hidden;' and then 'height:0;' to impact the layout as little as I could. There could be cross-browser styling issues here, my specific case didn't need anything special.

Monday, August 11, 2008

ASP.NET WebForms buttons and form submission

There's a problem with my previous solution to using Particletree's cool buttons - on IE7 (and only IE7) the click handler gets called twice. It turns out there's a proper way to handle form submission in ASP.NET WebForms - that lets me handle a POST the way I'd expect - and I just wasn't using it.
HTML (aspx):
<form runat="server">
   ...
   <button type="submit">...</button>
</form>
Notice that there's no 'onserverclick'.
Code-behind:
protected void Page_Load(object sender, EventArgs e)
{
    if (IsPostBack)
    {
        // handle form submission
    }
}
Shame on me for not learning the basics.