Strange behaviour of asp.net button on Firefox of pressing twice - asp.net

If I have this asp.net button:
<asp:Button ID="Button_Save" Width="150px" OnClick="Button_Save_Click" runat="server" Text="Save" />
In order to prevent the user to press the button twice to insert two data records, I added this in the code behind:
Button_Save.Attributes.Add("onclick", "this.disabled='true';" + ClientScript.GetPostBackEventReference(Button_Save_Data, null) + ";");
It works fine with IE and Chrome. However, in Firefox, every time the user presses the button once, I got two data records inserted.
After some time googling, I modified the button this way by adding: UseSubmitBehavior="false":
<asp:Button ID="Button_Save" Width="150px" UseSubmitBehavior="false" OnClick="Button_Save_Click" runat="server" Text="Save" />
Then it also works with Firefox, only one data record inserted. But then I will have to add that setting for every button on my web application. It requires a lot of work.
However, I think this is really a big problem if that is the case always with asp.net app running on Firefox. Or did I implement something wrong?
Thanks in advance.

You would be better off adding checks to your SAVE code to prevent duplicate POSTs. I've used code like yours and still had duplicate records because someone hit the Refresh button at the wrong time.
EDIT:
Here is the code I use. Key is to match a value on the server with a value coming back in the postback.
In Page_Load:
If Not IsPostBack Then
Session("rcdupdate") = Server.UrlEncode(System.DateTime.Now.ToString)
End If
In Page_Prerender
ViewState("rcdupdate") = Session("rcdupdate")
And in the Save routine
If Session("rcdupdate").ToString = ViewState("rcdupdate").ToString Then
... write the data to the database ...
Session("rcdupdate") = Server.UrlEncode(System.DateTime.Now.ToString)
End If

You can extend asp:button and add your new functionality, then fine/replace all of your asp:buttons. Going forward you can then change all your buttons in once place.

Related

Webform buttons displaying blank page

The bug I'm trying to solve is that the buttons on my .aspx page that correspond to methods in the .vb file all return a blank page without actually getting to the vb code (no breakpoints I've put on these methods get triggered). There is no redirect as the URL doesn't change it simply registers the button click and then its handler gives a blank page. I thought at first that this would have something to do with doPostBack but even after putting "CausesValidation="false" " this still continues. I've recreated the button in the designer window just to be extra sure that the button points to code and the program knows it but still no luck.
Here is what the button itself looks like:
<asp:Button ID="btnFreshTest" runat="server" CausesValidation="true" Text="Save User" ClientIDMode="Static" width="100px" ToolTip="Save changes" Height="35px" />
Here is what the visual basic method code looks like, yes its simple but this is for a test:
Protected Sub btnFreshTest_Click(sender As Object, e As EventArgs) Handles btnFreshTest.Click
Dim testString2 As String = "abc"
End Sub
Even if you don't have a solution given the lack of information, if you have any pointers that I could use like places to look for an error or somewhere to put a breakpoint with chrome tools, I would greatly appreciate it.
Ok, so we drop this into a page:
<asp:Button ID="btnFreshTest" runat="server" CausesValidation="true"
Text="Save User" ClientIDMode="Static"
width="100px" ToolTip="Save changes" Height="35px" />
So we see this:
Now do NOT JUST TYPE in the event stub - double click on the button above, and you now have this:
Protected Sub btnFreshTest_Click(sender As Object, e As EventArgs) Handles btnFreshTest.Click
Dim testString2 As String = "abc"
Console.WriteLine("Value of test string = " & testString2)
End Sub
And when we run, then we get this:
So, you may well have messed up the event, but if you JUST drop in that button (say a cut + paste from example code), then the event stub will not automatic wire up - you have to click on it.
And note VERY close that the button does not see, nor have a event defined IN the markup - but you will see it in the property sheet for that button like this:
And you can in markup actually force/type in the event define, and intel-sense will do this:
In fact you MUST DO this if the button is inside of a repeater/gridview/list view etc., since you can't double click on the button in the desinger anyway. So additional information here in regards to if some data repeating type of control is surrounding the button. A button is often part of MUCH markup, and depending on how it is nested, a simple click on the button is not always possible.
So, try typing in the OnClick= (and when you hit "=", you should get intel-sense, and try wire up the button that way.

Preventing the yellow screen of death

I'm having a problem with asp.net request validation. I have a basic page with a search field and a button. If the user inputs some illegal characters in the search field and clicks the button then of course I can validate his input in JS and everything's OK. However I have also a lot of LinkButtons not associated with the search functionality that do postbacks and when it happens I get the YSOD.
I know you can turn this feature off by adding ValidateRequest="false" in page directives or web.config, however I'd like to know if there is better and more elegant solution than simply disabling request validation completely.
Thanks.
you can use anti XSS Library to avoid cross scripting attack. check for this link AntiXSS asp.net .
and you can turn of the Yellowscreen of Death. by changing the CustomError mode to Remoteonly. so that remote user wont see the YSOD. only local server will see the YSOD
in web.config add line like this.
<configuration>
<system.web>
<customErrors defaultRedirect="yourErrorPage.html"
mode="RemoteOnly">
</customErrors>
</system.web>
</configuration>
Sounds to me like you need to put validation groups against your form elements (could be I'm misunderstanding the question).
(This would be easier if you'd have posted some code)
<asp:Panel runat="server" DefaultButton="btnSearch">
<asp:TextBox runat="server" ID="txtSearch" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="txtSearch" ValidationGroup="vgSearch" ErrorMessage="Search is required!" />
<asp:Button runat="server" ID="btnSearch" ValidationGroup="vgSearch" Text="Search" />
</asp:Panel>
<asp:LinkButton runat="server" ID="btnLogin" Text="Login" ValidationGroup="vgLogin" />
<asp:LinkButton runat="server" ID="btnCakes" Text="Cakes!" ValidationGroup="vgCakes" />
Anyway, the idea is that your search form and associated validators have one validation group, and your other buttons have other validation groups, then the validator won't fire when you click another button.
I'm not actually sure if you NEED the validation groups against individual link buttons, I don't think you do, but I'm putting 'em in there to demonstrate my point.
If I've completely missed the boat, let me know :)
EDIT:
I should mention that I've just thrown the above code together, can't guarantee it's all formatted correctly, etc, etc.
Oddly enough, the day after I attempted to answer this, a co-worked asked me to help with the same problem, so here's what I'm up to so far...
(Bare in mind that while I've been developing in .Net for a number of years, I've never had need to delve that deeply into the page life cycle, ViewState or any of the hideously complicated bits that keep better dev's up at night)
Initially, I thought that overriding the PostBack event in JavaScript would allow me to edit the form post and remove the offending characters, so I tried it with a simple alert, but the potentially dangerous Request.Form was still appearing, so whatever's causing it is happening before the PostBack event is being fired.
So, after investigating the page life cycle, overriding every method I could and doing a whole lot of debugging, I found that the error is being throw in the DeterminePostBackMode method.
Now, by my understanding, this method looks at the form post and converts it to a NameValueCollection, so I built my own NameValueCollection, stripping out the "<" character (I only tested with that character to start with).
Protected Overrides Function DeterminePostBackMode() As System.Collections.Specialized.NameValueCollection
Dim stream As New System.IO.StreamReader(Request.InputStream)
Dim nvCollection As New System.Collections.Specialized.NameValueCollection()
Dim _split() As String = stream.ReadToEnd().Split("&")
If _split.Length > 1 Then
For i As Integer = 0 To _split.Length - 1
Dim kv() As String = _split(i).Split("=")
Dim _key As String = HttpUtility.UrlDecode(kv(0))
Dim _value As String = HttpUtility.UrlDecode(kv(1))
If _value.Contains("<") Then _value = ""
nvCollection.Add(_key, _value)
Next
End If
'For Each s As String In nvCollection
' Response.Write(String.Format("<p>{0}={1}</p>", s, nvCollection(s)))
'Next
Return nvCollection
End Function
And that worked brilliantly, the offending value was being stripped out and the NameValueCollection was being returned without causing an error...
Except I was still seeing the error message.
At the moment, I've tracked it to the PreInit page event, and I'm trying to figure a way around it, I'll update this as I make progress.
UPDATE:
I'm now fairly sure that the issue ISN'T with the values being stored in the ViewState. After reading this excellent article on ViewState, I tried setting the value of a TextBox to "<script" declaratively, which means it shouldn't be stored in the ViewState, which means that the error isn't caused by processing being carried out on the ViewState.
I think.

LinkButton not firing ASP.NET validators

I have a form that currently uses an control to submit a form. Everything works perfectly. So now the new requirement is for the "submit' button to be a link. Changing it to a LinkButton control, without changing a SINGLE other thing, breaks the validation.
There is a bit too much code to post in a SO question and I know there's a bit of a lack of detail here, but is there any reason why a LinkButton wouldn't fire ASP.NET validation the same way a Button control would? In theory, they should both operate exactly the same, no?
The current submit button:
<asp:Button ID="btnSubmit" TabIndex="9" Text="Send" ValidationGroup="Forward" runat="server" />
The new submit button:
<asp:LinkButton ID="btnSubmit" TabIndex="9" Text="Send" ValidationGroup="Forward" runat="server" />
The Link button should fires the validation the same way a normal button does, my concerns in your case would be the following:
make sure these is nothing in the server side code stopping this.
make sure in the javascript code there is nothing stopping the "
ASP.NET controls that fire validation has a property called CauseValidation
Be sure all controls should fire validation, has this property set to True
Add attribute CauseValidation="True" to your control but if you want to fire this at particular line at code behind you can use validate the form by the following code:
FormID.Validate();
I know this is old but it has never answered. Did your validator have a "controlTovalidate"? Currently it would appear as if the validator was not firing but in reality it is. It just does not have anything that it is 'watching'. Hope if anyone reaches this thread that this helps even if it is just a little bit.
I was unable to determine the cause of this issue but was able to solve it:
I set the CausesValidation="false" and added at the top of the onclick event this.Validate(linkButton.ValidationGroup) this allows the event to get to the code behind and validation to occur.

Button not processing onClick method

I have a button on an ascx control that calls a method on the onClick event:
<asp:Button id="bUpdateText" onClick="FUpdate" ValidationGroup="Update" CausesValidation="False" Text="Update" cssclass="button" runat="server" />
Normally I use this control on it's own page and the button works. This time round however, I am loading this control into a Div that is present on the home page of my site (that way I can show the contents with a little bit of JQuery). However, when I bring the control in this way, the onClick event doesn't fire and I am not sure what could cause that.
Sorry I don't have any code sample but the nature of the site makes it difficult to provide any that would make sense.
In short, what would stop this event firing now?
p.s I have tried adding validation groups to all other buttons and validation controls on the page and there is only ONE form present on the page.
EDIT: I have only just added the validation stuff in to see if that does anything. By default it has been like this and still didn't work:
<asp:Button id="bUpdateText" onClick="FUpdate" Text="Update" cssclass="button" runat="server" />
As mentioned as well, this works when I use this control on it's own page (loaded directly into Default.aspx) so I don't think the case of onClick matters.
EDIT2: I have just noticed that when I click this button, other validation controls on my page are being triggered even though they have their own DIFFERENT validation group?! Taking these controls out doesn't help though.
Thanks.
I have found out what is causing the issue.
This control that I am now including is called on the Page_Finalize() and I am guessing that by this point the viewstate has forgotten it needs to do anything. Loading this control on the page load sorts it out.
Thanks for looking.
To start, if you set the 'causesValidation' property to false, you do not need a validation group.
Additionally, I believe that ASP cares about case when dealing with the OnClick command.
i.e. it should be OnClick not onClick
Yeah, annoying and small, but that might be your problem
You can use Firebug to see what happen in Update validationGroup. it looks like your page execute only client-side button click because of Update validationGroup.

AJAX Calendar extender on modalpopup returns null

I'm having some trouble getting a datetime from calextender on a modalpopup I have.
<asp:TextBox ID="txtPopEndDate" runat="server" Enabled="false"></asp:TextBox>
<img id="calButton" alt="" title="Show Calendar" src="~/App_Themes/Main/img/calendar.png"
runat="server" height="20" style="cursor: hand;" />
<ajax:CalendarExtender Animated="true" TargetControlID="txtPopEndDate"
runat="server" PopupButtonID="calButton"
Enabled="true" ID="calExtender" Format="dd/MM/yyyy"/>
are the controls I have to select the date, now when I press the ok button I handle the data including the date. However, if I try to fetch the date using calExtender.selectedDate property I get nothing. the same goes for manually getting the string from the textbox and parsin that.
I have to mention that the other data from textboxes and dropdowns on that popup work without a glitch. any help here would be greatly appreciated.
Your textbox has enabled = false. I think this spits out a disabled attribute set to true in the html, therefore the post of the form would not send the value. Why dont you want the textbox enabled?
Im also assuming your trying to grab the value after a postback ? Is that true?
yep,
in the meanwhile I found a solution to the problem. as you said, the textbox apparently needs to be enabled. this means the option for erroneous dates.
I got the value from the textbox and parsed it that way with a DateTime.TryParse to secure a correct date.
if anyone has a better option, let me know
We used Enabled="false" on TextBoxes linked to the CalendarExtender all through our application without a problem. Then I added a date picker to a page which refused to co-operate. The TextBox value was never available on PostBack.
I found the solution here:
http://www.west-wind.com/weblog/posts/2005/Dec/20/ASPNET-20-ReadOnly-behavior-change-when-EnableViewState-is-false
What I found was:
I could set ReadOnly = true, then retrieve the value from the Request on PostBack with TextBox1.text = Request[TextBox1.UniqueID].
I could use TextBox1.Attribute.Add("readonly", "readonly"), then the Text property was set as I expected.
I could not retrieve the value with Enabled = false; or TextBox1.Attribute.Add("disabled", "disabled")
We didn't have ViewState disabled on this page and we didn't get this behaviour on other pages, so I guess this behaviour can be triggered by something else too.

Resources