Rick Strahl's Web Log

Wind, waves, code and everything in between...
ASP.NET • C# • HTML5 • JavaScript • AngularJs
Contact   •   Articles   •   Products   •   Support   •   Search
Ad-free experience sponsored by:
ASPOSE - the market leader of .NET and Java APIs for file formats – natively work with DOCX, XLSX, PPT, PDF, images and more

Default Button Submissions in ASP.NET Pages


:P
On this page:

 

A couple of days ago David Cox pointed out a bug in my West Wind Web Store, where if the user submits the Item form by pressing Enter rather than clicking on the Add button, causes the form to fail.

 

The code for the Page_Load in this form looks something like this:

 

private void Page_Load(object sender, System.EventArgs e)

{

      if (!this.IsPostBack)

            this.DisplayItem();

}

private void btnSubmit_Click(object sender, System.EventArgs e)
{
...

}

 

with a btnSubmit handler routine below that is hooked up to the actual Submit button event. The handler among other things performs the task of re-displaying the item in case of failure or submitting the item to the shopping cart.

 

The code above works on the logic that any databinding and display of the item data only needs to happen during GET operations (ie, first access to the page) and any other operations on this page cause a submission of the form – IOW, the btnSubmit_Click() event would fire.

 

The code above works fine in most cases. If the user clicks the button – no problem. In most cases when the user just presses enter it also works as text fields on a form are implicitly self-submitting in HTML.

 

However, Internet Explorer is somewhat flakey in how it submits forms in this way. In this example, doing a trace reveals that the btnSubmit does not get POSTed when doing a submit from the TextBox. The same operation works fine in Firefox, which (correctly I think) submits the form with the single button in it.

 

There are several other forms in this application where Internet Explorer DOES submit the button. For example, on the OrderProfile.aspx page, users can press ENTER at any point and the form will sumit properly.

 

I've tried to understand what makes IE behave differently but I can't see any difference. Neither page has any special form submission or button code but one works the other doesn’t. Go figure.

 

The solution to the problem for the Item page of course is simple, IF YOU KNOW AND TEST FOR THIS SITUATION. And that’s a big if if the browser you’re testing with is sometimes working one way and sometimes another. The quick fix is:

 

private void Page_Load(object sender, System.EventArgs e)

{

      if (!this.IsPostBack)

      {

            this.DisplayItem();

      }

      else

      {

            // *** Must handle case where user is 'auto-submitting'

            //     without clicking the button.

            if ( Request.Form["btnSubmit"] == null )

                  this.btnSubmit_Click(this,EventArgs.Empty);

      }

}

 

which basically forces the form submission to occur if for whatever reason the form submission button hasn’t been provided.

 

It might actually make sense to create a DefaultButton property on the form and point it at a handler, and then hook this up in the OnLoad() event of a custom form base class:

 

// *** In base Page class

protected override void OnLoad(EventArgs e)

{

      base.OnLoad (e);

 

      if ( this.IsPostBack &&

this.DefaultButton != null &&

Request.Form[this.DefaultButton.ID] == null ) 

{

           

            MethodInfo Meth = this.DefaultButton.GetType().GetMethod("OnClick",

                               BindingFlags.Instance | BindingFlags.NonPublic);

            Meth.Invoke(this.DefaultButton,new object[1] { EventArgs.Empty });

      }

                 

}

 

Note that you have to use Reflection to make this happen since the OnClick() handler that fires the event is protected on the Button object. It actually took me a bit to figure out how to do this. I keep forgetting that you can’t access the Event directly by either calling the method or even as a Delegate like this:

 

DefaultButton.Click.Invoke(…)

 

In fact, I don’t know of a way to directly access the event in any way other than assignment (+=) or removal (-=) from client code. Hence the requirement for Reflection. The above also isn’t truly generic – it works on internal knowledge (and convention in the .NET framework) that there’s an OnClick() method that is responsible for firing the event. If there wasn’t such a ‘firing method’ handy, a lot more work would be needed to get the EventInfo object, retrieve the RaiseMethod() and then fire it on the Page object. Yuk…

 

It sure would be a lot nicer if we could somehow get a reference to the Delegate:

 

EventHander e = DefaultButton.Click as EventHandler;

e.Invoke(…);

 

But no such luck. Maybe somebody knows of an easier way to do this.

 

Anyway, the code above works reliably only if you have a single submit button. If you have more than one button submission on a form you’d need a slightly more elaborate scheme that checks all possible button submissions to make sure you don’t submit if another button was submitted. If you use a common naming scheme (like btn prefix) this is easy and you can modify the code above to check for any button that starts with the prefix in the Form[] collection.


The Voices of Reason


 

Mike McDonald
December 29, 2004

# re: Default Button Submissions in ASP.NET Pages

I don't know if this has any connection to why the handler routine wouldn't fire, but I can tell you why the btnSubmit gets POSTed from the OrderProfile page but not from the Item form page.

It seems that IE has a bug (which has been there since at least version 4.0 I believe) where it won't POST the button value if there is only *one* input field on the form (and you hit ENTER instead of clicking on the button). If there are two or more (non-button and non-hidden) input fields, the submit button does get POSTed. This only affects IE, not any other browsers I've tried.

It doesn't seem to matter how many buttons are on the form, but the number of other input fields. I had previously thought that including an extra hidden input field would 'fix' this issue, but even that doesn't seem to work in IE6 right now.

Skip Lutz
January 21, 2005

# re: Default Button Submissions in ASP.NET Pages

Here is how you get around the bug. Add a input control textbox (System.Web.UI.WebControls.TextBox) then do the following:
1) Change the width to 0
2) Change the readonly property to true.

Worked for me!
Skip Lutz

Jennifer Wardwell
January 27, 2005

# re: Default Button Submissions in ASP.NET Pages

I tried adding a second input control textbox with width=0 and readonly=true but that did not work for me.

Mike Mantis
January 28, 2005

# re: Default Button Submissions in ASP.NET Pages

Thanks Skip, that worked perfectly!

derek hatchard \\ ardent dev
February 05, 2005

# ASP.NET form with single textbox does not post as expected on ENTER in Internet Explorer


Scottie
February 23, 2005

# re: Default Button Submissions in ASP.NET Pages

Wow that zero-width readonly textbox worked wonders for me also! Thank you very much!

Flushy
March 16, 2005

# re: Default Button Submissions in ASP.NET Pages

Is there any better workaround ?

Is this bug described on MSDN ?

Thank you for reply...

Yuji
March 18, 2005

# re: Default Button Submissions in ASP.NET Pages

Here is another quick fix via CSS

<input type="text" style="display:none" runat="server" />

For some reason I could not get the input type to take the width. And it also showed the button. So that would not work for me. But the above works like a champ.

Hope this helps

Yuji
March 18, 2005

# re: Default Button Submissions in ASP.NET Pages

The above I meant that the textbox would show up. Not the button

xiang qin
June 03, 2005

# re: Default Button Submissions in ASP.NET Pages

To Yuji:
Your suggestion worked super well for me! Thank you very much!
The above I forgot to mention who I am thanking.

sudeep
June 09, 2005

# re: Default Button Submissions in ASP.NET Pages

adding zero-width readonly textbox worked for me.. thanks a ton :)

Chingis
June 29, 2005

# re: Default Button Submissions in ASP.NET Pages

I don't think this is a IE bug. I know this because I have the same problem right now and my submit button would work on 2 of the servers and does not work on the 3rd one. Unfortunatly the 3rd one is the one I host my web sites and databases.

g
July 22, 2005

# re: Default Button Submissions in ASP.NET Pages

fg

Adam Hewgill
July 27, 2005

# re: Default Button Submissions in ASP.NET Pages

Width="0" textbox still visible? Try setting the BorderWidth="0" as well.

But this workaround works for me too. Thanks.

Josh
August 11, 2005

# re: Default Button Submissions in ASP.NET Pages

Wow, what a retarded bug. This was driving me crazy - I am SO glad I found these messages!! Thank you!

Yasir
August 16, 2005

# re: Default Button Submissions in ASP.NET Pages

The same thing can be achieved by using this code on page load:

Page.RegisterHiddenField( "__EVENTTARGET", myButton.ClientID );

Where myButton is the button you want to be default.
This method will NOT work when you have <asp:Button> objects on the page. In many browser versions (see above) the Button’s will post automatically, and their name/value pair will override the pre-set __EVENTTARGET.
Also, certain controls will re-set the __EVENTTARGET to an empty string.

Thanks

Yasir
August 16, 2005

# re: Default Button Submissions in ASP.NET Pages

In order to call this event, you will have to put focus on any of the form element. For instace, I did this by using:

onload=Form1.txtcity.focus() in <Body> tag to put focus on the text field just as the page loads.

Thanks

Doug
August 17, 2005

# re: Default Button Submissions in ASP.NET Pages

I had this problem, but found the real cause was because i was running some of my own JS in the form's onsubmit event (validation). If i did not run any of my own code then the submit worked just fine via the enter key.

IE 6

How about multiple buttons
August 29, 2005

# re: Default Button Submissions in ASP.NET Pages

We have a similar problem involving several buttons whose properties are initally False until the page is posted back. When set Vislble=True on Page Reload the events associated with these buttons no longer work. The wierd thing is that they do work if you use Firefox, or when hosted with Win 2000 Server. The problem seems be a combination of Server 2003 + IE.

Luca
September 16, 2005

# re: Default Button Submissions in ASP.NET Pages

0 width + readonly Works great! Thanks :)

Tim McOwan
November 10, 2005

# re: Default Button Submissions in ASP.NET Pages

I can't believe it worked, but it worked. Width 0, readonly = true.

Eric
November 15, 2005

# re: Default Button Submissions in ASP.NET Pages

You're right. Seems to be an IE bug.

To fix try this: <input name="hidden_fld" type="text" id="hidden_fld" border="0" style="width:0px;visibility:hidden;display:none;" />

Johnnie
November 17, 2005

# re: Default Button Submissions in ASP.NET Pages

Does the width=0 and readonly=ture work on Firefox? Doesn't seem to for me.

Sharp Zero
December 03, 2005

# re: Default Button Submissions in ASP.NET Pages

this is the craziest solution... IE makes us crazy..... it works for me too. I spent one night to figure it out...

the thing is to get the job done.


ZERO WIDTH thanks

SolutionsGuy
December 09, 2005

# re: Default Button Submissions in ASP.NET Pages

I dont know that this is a bug, its just IE handles it differently. Probably more appropriately because they understand the framework and try to make it closer to a windows forms based system. You will notice that hitting enter on a textbox will do a postback. So, some event is being fired, its just not the click event for the button. It is the text_changed event for the textbox. So, simply create a method for doing your form submission logic and call it in both your button click and textbox change events!

Tom
December 31, 2005

# re: Default Button Submissions in ASP.NET Pages

Thanks SolutionsGuy, makes sense to me

Raghu
January 09, 2006

# re: Default Button Submissions in ASP.NET Pages

I have another problem.. I have 3 submit buttons each performing differnt tasks. But I want to make 3 rd button as my default button when ever user clicks enter key

Harshal Deshpande.
July 12, 2006

# re: Default Button Submissions in ASP.NET Pages

It works perfectly... Thanks a lot ;0)

meska
October 20, 2006

# re: Default Button Submissions in ASP.NET Pages

Sorry, but the event of my submit button is not working in IE... in FIREFOX everything is running as i predict. What seems to be the problem?
I did not found a solution for this problem above... what to do?

Michael Lang
November 09, 2006

# re: Default Button Submissions in ASP.NET Pages

There is an issue in ASP.NET 2.0 with textbox's not firing the submit button's click event when the user presses enter within the text field. You can fix this by using ASP.NET 2.0 Defaultbutton attribute on either the form element or a panel object.

Scott Guthrie post a great blog on this topic some time back here...

http://weblogs.asp.net/scottgu/archive/2005/08/04/421647.aspx

I have seem some discussion that in some instances ppl are having problems with the default button in that instance I would try something like this....
<asp:textbox id="t1" runat="server onkeypress="submitForm()" />


<script type="text/javascript">

function submitForm()
{
if (event.keyCode == 13)
{
event.cancelBubble = true;
event.returnValue = false;
theForm.t1.click();
}
}
</SCRIPT>


Hope this helps...

tony
March 27, 2007

# re: Default Button Submissions in ASP.NET Pages

Add borderwidth="0px" solve my problem to hidden my textbox on firefox.

Thanks

Mohan
April 04, 2007

# re: Default Button Submissions in ASP.NET Pages

Thanks it's very useful

Getting Started
April 24, 2007

# ASP.NET Forums - How to Have RETURN on textbox activate submit button?


KSh
April 30, 2007

# re: Default Button Submissions in ASP.NET Pages

I tried the above mentioned but its not workgin for me in IE7.
Hears the code.

<form id="form1" runat="server" defaultbutton = "btnLookup" defaultfocus="txtCompany">
<td>
<autoComplete:TextBox ID="txtCompany" Name="txtCompany" VarName="gCompanies" ErrorLabel="errorspan"                                                                      AllowNonMatching="false" ErrorText="Company not covered" runat="server" DisableControl="ctl00_btnLookup" />
</td>
<td>
&nbsp;<asp:ImageButton ID="btnLookup" runat="server" CssClass="" 
EnableViewState="False" EnableTheming="false" OnClientClick="return gController.LookupCompany();" />
</td>
<td>
</form>



I want to call OnClientClick="return gController.LookupCompany();" on click of enter in textbox txtCompany. The above given code works properly in Firefox but not in IE7.

As suggestd i tried putting

<input name="hidden_fld" type="text" id="hidden_fld" border="0" style="width:0px;visibility:hidden;display:none;" />

in first td, but it did not work for me.

James
October 12, 2007

# re: Default Button Submissions in ASP.NET Pages

This worked for me...

if (!IsPostBack)
{
//set the default button so that IE submits on hitting enter (for the Search)
this.Form.DefaultButton = btnSearch.UniqueID;
}

you can set the DefaultButton in the page declaratively but my Form sits in the MasterPage..

Abdullah
February 22, 2009

# re: Default Button Submissions in ASP.NET Pages

Mr. James you are right so the best solution is your commet:
here is the code in VB.Net:

form1.DefaultButton = tbtn.ClientID

Andornot - Blog
January 27, 2010

# Single Search Boxes and the Submit Button

Single Search Boxes and the Submit Button
 

West Wind  © Rick Strahl, West Wind Technologies, 2005 - 2019