The wrong information being displayed when user clicks the back button - asp.net

I've created a simple example to show what I'm having problems with. Place a asp.net checkbox on a page and an asp.net textbox on the same page. In the code behind (using vb.net), put code that displays something in the textbox when the checkbox is checked and displays an empty textbox when the check box is not checked. Simple, right? Now toggle back and forth several times with the checkbox checked/unchecked and the textbox has content/no content. Everything works fine - right?
Now click your back button on your browser a few times. The results being displayed with each back button click is opposite - check box is checked yet nothing in the textbox. Checkbox is unchecked and there is text in the textbox. It doesn't matter where you put the vb code (page load, checkedchanged) - same results.
I'm thinking that it has something to do with the timimg of the page being saved in cache. Something like the page is being saved in the cache while the checkmark is firing the "click" event yet the code to fill the textbox has not yet been fired. Then again I could be completely off the mark and it is something real simple that I'm doing wrong.
Any ideas/thoughts/help would be greatly appreciated.
Sample Code:
ASPX:
<asp:CheckBox id="ChkBox1" runat="server" AutoPostBack="True" text="Sample" /><br />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
VB:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If ChkBox1.Checked = True Then
TextBox1.Text = "Checked"
Else
TextBox1.Text = ""
End If
End Sub

This is the way it should be.
Browsers remember every time you post back to the server. Your page is posting back whenever the checkbox state changes.
When the checkbox state is checked, the textbox is indeed empty. This is when the postback occurs. Your server side code sets the text value, and you see it in the browser.
But your back will remember what you sent, that was a checked checkbox and empty text.
The reserve case happens when you uncheck.
If you refresh one of those back pages with a F5, your browser should ask to send back post data. And you will get back to the expected state.
Tell the browser not to cache the content(if you want the browser to forget it):
Not VB code, but I am sure you will find similar functions on VB.net too.
context.Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
context.Response.Cache.SetNoStore();

Related

How to update an onscreen price without refreshing page when using DDL

I am setting up a page to allow users to create their own pool cues. As they select a feature they want on their cue from a dropdown list it needs to update the price onscreen but not refresh the whole page. I'm guessing I would use an update panel ? Not sure where and how to add it. The selected value passed to the VB code is the extra price to pay (Eg: £10 extra for a jointed cue). Here's what I have so far..
FRONT END
<asp:DropDownList ID="ddlJoint" runat="server" AutoPostBack="true" RenderMode="Partial" style="margin-bottom:10px" height="33px" font-size="1.6em" OnSelectedIndexChanged="ddlJoint_SelectedIndexChanged">
<asp:ListItem Value="">Cue Joint:</asp:ListItem>
<asp:ListItem Value="10">3/4 Join</asp:ListItem>
<asp:ListItem Value="0">One Piece</asp:ListItem>
</asp:DropDownList>
<br>
<asp:Label ID="lblTotal" runat="server" Text="Price:"></asp:Label>
VB
Protected Sub ddlJoint_SelectedIndexChanged(sender As Object, e As System.EventArgs)
session("joint") = ddlJoint.SelectedValue
session("total") = session("joint") + session("tip")
lblTotal.Text = session("total") + 180
End Sub
Your gut feelings are correct. You need an update panel. Here is an article how to use update panel with drop down list:
http://www.c-sharpcorner.com/uploadfile/Dorababu742/drop-down-list-in-ajax-update-panel/
Using an update panel is a great was to “avoid” having to wire up your own AJAX calls and updates.
And it gets rid of post-backs rather nice.
(So hitting the browser back button does not go to a previous post back for that given web page).
Make a blank test web form.
In web form design mode, simply:
From tool box, simply drag + Drop in the scrip manager.
(You can search for script in search box, but you find this under AJAX Extensions.
Now drop in an update panel
(Again you find this under AJAX Extensions).
Now drop in a button and text box “inside” of the update panel.
And for fun, let’s drop in another button below (outside) of the update panel.
Double click on the first button (to bring up vb code editor).
Simply type in this code:
me.TextBox1.Text = "post without post back"
Behind that button again double click, and write this code
me.TextBox1.Text = "post back"
Your form will look like this:
Note how when you click the button inside the update panel, the browser does not show or “light up” the back button.
However, if you hit the button outside of the update panel, you see the browser “spin” – a post back occur and the back button becomes active.
For you existing page, you can drop in the scrip manager near the top.
Then where your controls are drop in an update panel.
Then select the controls you want and drag + drop (or even cut + paste into the update panel area).
The beauty of above is you really don’t have to change your coding habits or learn JavaScript to “wire” update areas of a web page that update without post-backs.
The resulting vb.net code looks like this:
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Me.TextBox1.Text = "hello"
End Sub
Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Me.TextBox1.Text = "hello with post"
End Sub

server-side ASP.NET onclick handler doesn't fire when submitted from browser on Apple device

I have a form which has two panels, one which captures a username and password via textboxes and the other which does the serious stuff. Only one panel shows at any one time. The login panel shows until a user has logged in successfully, then the other panel shows.
On iPads and iPhones, using Safari or Chrome, the "Proceed" button of the login panel posts back, but the handler doesn't fire:
<asp:Button ID="cmdProceed" runat="server" Text="Proceed" OnClientClick="cmdProceedClientClick();" />
Protected Sub cmdProceed_Click(sender As Object, e As System.EventArgs) Handles cmdProceed.Click
Dim cmdProcSP As SqlCommand = dbWeb.GetStoredProcCommand("uspAuthenticate")
...
End Sub
The "same" code (I understand that ASP.NET may generate different code for different browsers) works fine on the latest IE, Firefox and Chrome on a PC, and also in Chrome on my Moto-G.
Trawling through SO, I find instances of where a postback isn't triggered at all, especially when there is also a client-side click handler defined, but that is not the problem, the postback works, but the ASP.NET click handler doesn't fire.
I found a nice trick to view the page source in Safari but nothing looks to be amiss or missing.
Happily I have a workaround for this problem in this instance, just calling the handler myself in Page.Load
If Request("txtUserName") <> "" And Request("txtPassword") <> "" Then cmdProceed_Click(Nothing, Nothing)
but I'd still like to know what's going wrong and an answer might help someone else.

Open a Popup and redirect to another aspx page by same button click event in asp.net

I have a busienss requirement that, it needs to open a pop and also page redirection to be done in the same Submit button click event, presently i did both, but only Page redirection is happening, the popup is not working.
On commenting the Page redirection, the popup is working. Can anyone give me the solution for this?
Eg.
Private Sub wbtnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles wbtnSubmit.Click
wbtnSubmit.Attributes.Add("OnClick", "win_openPopUp();")
ClientScript.RegisterStartupScript(Page.GetType(), "win_PopUp", "win_openPopUp();", True)
'Also i need this redirection also...'
If ViewState("Mode") <> "E" Then
AppHelper.PageRedirect("2220", Localization.LocalizedLables.MessagesModules.MyMessages, AppHelper.PageMode.Add)
Else
AppHelper.PageRedirect("2113", Localization.LocalizedLables.MessagesModules.MyMessages, AppHelper.PageMode.Add)
End If
End
In above code, any one is working... i need, after the pop close the page should be redirected to my specifed page.
This line of code
ClientScript.RegisterStartupScript(Page.GetType(), "win_PopUp", "win_openPopUp();", True)
what does is to execute javascript win_openPopUp(); when it is reloaded the same page that did the postback . That's not what you want.
This line
wbtnSubmit.Attributes.Add("OnClick", "win_openPopUp();")
should be placed in page_load event, not here where the event has already been triggered. But you don't need to do that, as you can add this attribute in the button asp tag.
< asp:Button ID="wbtnSubmit" Text="" runat="server" OnClientClick="win_openPopUp();">
If you need more information about popups you can read
http://forums.asp.net/t/1283761.aspx?Response+Redirect+URL+and+target+_blank+

Dropdown in .net usercontrol not maintaining state

This is probably something fundamental and stupid that I've missed, but the various workarounds are causing me such huge headaches that really, I need to understand the basic problem here in order to find the best solution.
I have a usercontrol which contains a drop-down list.
<asp:DropDownList ID="ddlOrderStatus" AutoPostBack="true" runat="server" CssClass="textbox">
<asp:ListItem value="8">Pending</asp:ListItem>
<asp:ListItem value="9">On Hold</asp:ListItem>
<asp:ListItem Value="11">Complete</asp:ListItem>
<asp:ListItem Value="12">Cancelled</asp:ListItem>
</asp:DropDownList>
It does nothing in its Page_Load event.
This is in turn contained in a page which, in it's Page_Load event does some databinding on some repeater controls on the page but doesn't touch the control containing the ddl. There is no ajax on the page.
The dropdownlist is - clearly - set to autopostback = true. The postback code looks like this:
Private Sub ddlOrderStatus_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlOrderStatus.SelectedIndexChanged
Dim ddl As DropDownList = DirectCast(sender, DropDownList)
Dim currentsorting As String = Request.QueryString("sort")
Dim currentpaging As String = Request.QueryString("page")
Response.Redirect(String.Format("~/admin/orders/Manage/0?sort={0}&page={1}&status={2}", currentsorting, currentpaging, ddl.SelectedValue))
End Sub
So when the ddl is changed, the page actually does a double postback. I see no way to avoid this as I need to do a postback to get the value in the ddl and then another postback to get some new data from the server based on that value.
Anyway, the long and the short of it is that when you do this the dropdownlist fails to maintain its state. So you select a value, the code does the job it's supposed to - gets the selected value then posts back again returning the new expected set of data - and then on loading again the dropdownlist is back in its default form.
This is a pernicious problem for me because of that double-postback: if I try and set the value of the ddl to equal what's in the querystring I have, effecitvely, set it to that value permanently because Page_Load - where the value is set - occurs before events are processed and so the value stays unchanged. I tried moving the code which changed the selectedvalue of the ddl into Render, but it seemed that although the selected value had changed as far as the user could see, the selected value was still the default value during processing and was treated as such.
I also tried setting the selectedValue in session and then clearing it as soon as it was populated. That worked for some scenarios, but unfortunately this page also contains some javascript that can cause it to post back - and you can't set session from client-side javascript. So that idea had to go out the window.
I'm at a loss here - this apparently simple problem has eaten a whole day of my time. Can anyone either tell me why state isn't being maintained on this control and/or suggest a way I get it to show the right value after postback without turning the selection into a permanent one?
Cheers,
Matt
In your page load:
// Only set the selected order status when the page first loads, but not on postbacks.
if( !Page.IsPostback )
{
ddlOrderStatus.SelectedValue = Request.QueryString("status");
}
Footnote:
I see no way to avoid this as I need
to do a postback to get the value in
the ddl and then another postback to
get some new data from the server
based on that value.
You could do it from javascript
I'll preface this by saying that I do my ASP.NET programming in C# and use GridViews, but the following should apply to your situation regardless:
Is it necessary for you to use the query string to hold this data? If you've declared your paging and sorting controls on your ASPX page, you can access them and their values directly in your codebehind (as Greg demonstrated in the above code by not performing a FindControl call). Has the user control setup prevented you from being able to u this? Are you instantiating the user control containing this drop-down list on a page, and then trying to access the value of the drop-down list from the page's codebehind itself, rather than the user control's code behind?

How to avoid InvalidOperationException when setting the defaultbutton in ASPX content

I am trying to set a default button in my ASPX page. I have a master page so the form is there. I have a panel in the content page that holds a table that organizes a number of textboxes, dropdowns and other inputs. The last row of the table holds some buttons, one of which I want to be the default button. After doing some research, I have tried the following with no success.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
pnlHolder.DefaultButton = cmdSearchJob.ClientID
I have also tried
pnlHolder.DefaultButton = cmdSearchJob.UniqueID
and
Dim cmdDef As Button = pnlHolder.FindControl("cmdSearchJob")
pnlHolder.DefaultButton = cmdDef.UniqueID
but both throw the exception "The DefaultButton of 'pnlHolder' must be the ID of a control of type IButtonControl.".
I have seen some Javascript solutions, but was hoping to just be able to set the defaultButton for the panel.
Try setting the DefaultButton of the parent Form.
C#:
this.Page.Form.DefaultButton = cmdSearchJob.UniqueID;
VB?:
me.Page.Form.DefaultButton = cmdSearchJob.UniqueID
Similar issue here: Allow Enter key to login in asp.net?
Try setting it to:
cmdSearchJob.ID
The panel will call FindControl to get the Client ID itself
Can you set this inside the control on the front-end?
<asp:Panel id="pnlHolder" DefaultButton="cmdSearchJob">
<asp:Button id="cmdSearchJob" runat="server" Text="Search" />
</asp:Panel>
Also, this may worth knowing, what type of object is cmdSearchJob? Is it a standard asp.net button control?
Finally found what it was. Tried adding another button with no CSS, etc. that just popped up a javacsript alert() for testing. Was able to set that as the default button when it was outside the table. As the submit button is one of a series of buttons (not a very pretty UI, but user requirements and all that) in the table, I used this additional button and set its style to display:none and have it call the same subroutine in the code behind.
So, short answer, it wasn't seeing it in the table.
Thanks everyone for your input.
I still have no idea why it wouldn't set the button.

Resources