AutoPostBack and parameter value after browser Back - asp.net

When using postback and then browser Back button, previous content is shown correctly, but the parameter that triggered postback has the latest value - it is not returned to the value it had before it triggered postback. This creates an invalid state.
In the example, dropdown has AutoPostBack set to true.
After I type "a2" and change dropdown value to "text2":
After I type "a3" and change dropdown value to "text3":
After Back:
Turning of browser cache programmatically didn't help, as it gives "Document Expired" on browser Back action.
After going Back, I wish that parameters match the content which is generated with those parameters, specifically the ones that are AutoPostBack. Is there a desired way of getting that behavior?
Code:
aspx
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true">
<asp:ListItem Text="text1" />
<asp:ListItem Text="text2" />
<asp:ListItem Text="text3" />
</asp:DropDownList>
<div>Server content - <asp:Label ID="ServerContent" runat="server" /> </div>
aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
ServerContent.Text = string.Format(
"received values: {0}, {1}", TextBox1.Text, DropDownList1.SelectedValue);
}

It is still not very clear what you are trying to do. The DropDownList changes, the server does a form post, you get a response and then you want that response in the previous state (before form post)? Seems like a weird rquirement. If a user goes back because he made a mistake, he changes the value and then does a PostBack again. No harm done.
But if you really want to set the value to it's default, you need to set the value of the DropDownList with JavaScript when the page has not done a PostBack. Take a look at my snippet below, it gives the desired results. It sets the SelectedIndex at 2 when the page is loaded, but does not when a PostBack is performed so the new value is still visible. Now when the user goes back the script is still present and will set the DropDownList to it's default value again.
<asp:DropDownList ID="DropDownList1" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" AutoPostBack="true">
<asp:ListItem Text="aaa" Value="aaa"></asp:ListItem>
<asp:ListItem Text="bbb" Value="bbb"></asp:ListItem>
<asp:ListItem Text="ccc" Value="ccc"></asp:ListItem>
</asp:DropDownList>
Code behind
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "setValue", "document.getElementById('" + DropDownList1.ClientID + "').selectedIndex = 2;", true);
}
}

I had to keep values for certain fields in additional hidden fields and use them on the client. The same example with "solution":
aspx
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true">
<asp:ListItem Text="text1" />
<asp:ListItem Text="text2" />
<asp:ListItem Text="text3" />
</asp:DropDownList>
<asp:HiddenField runat="server" ID="DropDownList1ValueCarrier" ClientIDMode="Static" />
<div>Server content - <asp:Label ID="ServerContent" runat="server" /> </div>
aspx.cs
protected void Page_PreRenderComplete(object sender, EventArgs e)
{
DropDownList1ValueCarrier.Value = DropDownList1.Text;
}
js
$('#DropDownList1').val($('#DropDownList1ValueCarrier').val());

Related

Asp.net C# - checkbox control won't stay true after code-behind runs

Front HTML
<asp:CheckBox ID="chkSend" runat="server" Text="Send?" />
The code that triggers the code behind
<asp:DropDownList ID="ddlStatus" OnSelectedIndexChanged="ddlStatus_SelectedIndexChanged" AutoPostBack="true"
runat="server" DataValueField="Id" DataTextField="Status" />
The code that runs in the code behind
protected void ddlStatus_SelectedIndexChanged(object s, EventArgs e)
{
this.chkSend.Checked = True;
}
When get back to the front end , the checkbox isn't checked. Any Ideas?
If it helps, this particular view is using Multi-views to which I'm new to.

How to set a asp:DropDownList SelectedValue to a Session Variable?

There are several articles describing how to do this is code behind however:
Is it possible to set the value of a dropdownlist to a session variable on the aspx page?
I am using SqlDataSource to populate the dropdownlist so do not wish to add code behind if it can be avoided.
<asp:DropDownList ID="ddl" runat="Server" DataSourceID="sqlDS" DataValueField="ID" DataTextField="TEXT" AppendDataBoundItems="true">
<asp:ListItem Text="" Value="" Selected="True" />
</asp:DropDownList>
<asp:SqlDataSource ID="sqlDS" runat="Server" SelectCommand="spDS" SelectCommandType="StoredProcedure" />
Set Session("ID") as selected value on load?
The dropdown list is already populated from the sqldatasource. I just want to set the initial value on page load.
You need a server side code in order to use Session. The following code doesn't requires code behind file, but again the code inside script will run at server side.
<asp:DropDownList ID="ddl" runat="Server"
DataSourceID="sqlDS"
DataValueField="ID"
DataTextField="TEXT"
AppendDataBoundItems="true"
OnSelectedIndexChanged="ddl_SelectedIndexChanged"
AutoPostBack="True">
<asp:ListItem Text="" Value="" Selected="True" />
</asp:DropDownList>
<asp:SqlDataSource ID="sqlDS" runat="Server"
SelectCommand="spDS" SelectCommandType="StoredProcedure" />
<script runat="server">
protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
Session["SelecteValue"] = ddl.SelectedValue;
}
</script>
Note: Make sure AutoPostBack="True" for DropDownList.
Do not mix code with markup. It makes sense to separate them for many reasons. So ASPX will have just the presentation, and CS/VB just the code logic.
When you compile/deploy your side to production - there will not be "the second page" - only ASPX page will remain. Code will be compiled into a DLL.
you'll need an event for your dropdown list on change. Are you using C# or VB.net for your codebehind?
add to onSelectedIndexChanged="ddl_OnSelectedIndexChanged"
to your code behind add:
{this is C# vb is similar}
protected void ddl_OnSelectedIndexChanged(Object sender, EventArgs e)
{
Session["selectedID"] = ddl.selectedValue;
}
to your page load, add
if (isPostback)
{
ddl.selectedValue = Session["selectedID"];
}

How to Ensure a DropDownList is Required if a given Radio Button is selected?

I have a RadioButtonLIst as follows:
<asp:RadioButtonList runat="server" ID="Location" ValidationGroup="formVal">
<asp:ListItem Value="Beverly Hills" />
<asp:ListItem Value="Seattle" />
</asp:RadioButtonList>
<asp:RequiredFieldValidator runat="server" ID="rfvLocation"
ControlToValidate="Location">
</asp:RequiredFieldValidator>
If the first radio button is selected, I need to require a selection in the following dropdownlist:
<asp:DropDownList runat="server" ID="Food" ValidationGroup="formVal">
<asp:ListItem Text="Chicken" Value="Chicken"></asp:ListItem>
<asp:ListItem Text="Beef" Value="Beef"></asp:ListItem>
<asp:ListItem Text="Fish" Value="Fish"></asp:ListItem>
</asp:DropDownList>
Would I use a CustomValidator to accomplish this? If so, what validation expression should be used? If a CustomValidator isn't a good fit, which validator is suggested?
Thanks much:)
UPDATE: Added the following to code behind
protected void LocationChanged(object sender, EventArgs e)
{
if (Location.SelectedIndexChanged == true)
{
rfvFood.Enabled = true;
}
else rfvFood.Enabled = false;
}
Is this correct?
You could do the following:
add a RequiredFieldValidator for the DropDownList and set its enabled property to false
set AutoPostBack=true on the RadioButtonList
in code behind, handle the RaditButtonList's OnSelectedIndexChanged event
Here, add logic that enables or disables the RequiredFieldValidator depending on RadioButtonList's selected item
If you don't like the whole page refreshing when the user chooses an option, wrap these controls up inside an UpdatePanel.

Telerik RadDock for ASP.NET AJAX initialization problem

I've run into a problem while using Telerik RadDock control for asp.net ajax. I'm generating the dock layout dynamically and there are multiple page configurations retrieved from the database. The thing is that I need to use post data before handling LoadDockLayout event, because there is a dropDownList which gives the ability to select one of avialable configurations.
I may be missing something, but it appears to me that LoadDockLayout event is fired before PreLoad event (it looks like the LoadDockLayout is fired before ProcessPostData method call) and before dropDownList selectedIndexChanged event, so I don't have the value I need to initialize dock layout properly.
I was thinking of converting my dropDownList to client side control and passing the selected value in query string, but it seems for me to be an ugly solution. Any advices would be appreciated.
Thanks in advance.
The RadDockLayout.LoadDockLayout event is fired at Page.InitComplete before any post data can be handled. If you want to load different controls based on a DropDownList selected item, you can do it by checking the parameters sent from the client. Here is an example on how you can retrieve them:
ASPX
<asp:Label ID="Label1" EnableViewState="false" runat="server" />
<asp:DropDownList ID="Dropdownlist1" runat="server" AutoPostBack="true">
<asp:ListItem Text="text1" Value="val1" />
<asp:ListItem Text="text2" Value="val2" />
<asp:ListItem Text="text3" Value="val3" />
<asp:ListItem Text="text4" Value="val4" />
</asp:DropDownList>
C#
protected void Page_Init(object sender, EventArgs e)
{
if (IsPostBack)
{
var selValue = this.Request.Params.Get("Dropdownlist1");
Label1.Text = "EVENTTARGET: " + this.Request.Params.Get("__EVENTTARGET") + "<br/>Value sent: " + selValue;
}
}

Getting control that fired postback in page_init

I have a gridview that includes dynamically created dropdownlist. When changing the dropdown values and doing a mass update on the grid (btnUpdate.click), I have to create the controls in the page init so they will be available to the viewstate. However, I have several other buttons that also cause a postback and I don't want to create the controls in the page init, but rather later in the button click events.
How can I tell which control fired the postback while in page_init? __EVENTTARGET = "" and request.params("btnUpdate") is nothing
It is possible to determine which control caused a PostBack by looking at Request.Form["__EVENTTARGET"]. The problem with this is that button ids will not show unless you set their UseSubmitBehavior to false. Here's an example:
.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
switch (Request.Form["__EVENTTARGET"].ToString())
{
case "ddlOne":
break;
case "btnOne":
break;
case "btnTwo":
break;
}
}
}
.aspx
<form id="form1" runat="server">
<asp:DropDownList ID="ddlOne" AutoPostBack="true" runat="server">
<asp:ListItem Text="One" Value="One" />
<asp:ListItem Text="Two" Value="Two" />
</asp:DropDownList>
<asp:Button ID="btnOne" Text="One" UseSubmitBehavior="false" runat="server" />
<asp:Button ID="btnTwo" Text="Two" UseSubmitBehavior="false" runat="server" />
</form>

Resources