How to set a asp:DropDownList SelectedValue to a Session Variable? - asp.net

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"];
}

Related

AutoPostBack and parameter value after browser Back

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());

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.

RadioButtonList inside UpdatePanel inside Repeater, Can I?

I have a repeater with a RadioButtonList inside the ItemTemplate, but when the RadioButtonList.OnSelectedIndexChanged event fires it generates a full postback. What have I done wrong in my code below? How can I get the OnSelectedIndexChanged to generate an Async Postback?
<asp:UpdatePanel runat="server" ID="UpdatePanel2">
<ContentTemplate>
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="sqlOptions">
<ItemTemplate>
<asp:UpdatePanel runat="server" ID="pnlA">
<ContentTemplate>
<strong>
<%# Eval("Name") %></strong><br />
<asp:RadioButtonList ID="RadioButtonList1"
DataSourceID="sqlOptionValues" runat="server"
DataTextField="id" DataValueField="Id" AutoPostBack="true"
OnSelectedIndexChanged="LoadPrice"
ValidationGroup="options" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1"
ForeColor="Red" runat="server"
ControlToValidate="RadioButtonList1"
ErrorMessage="Required Field"
ValidationGroup="options" />
<asp:SqlDataSource ID="sqlOptionValues" runat="server"
ConnectionString="<%$ ConnectionStrings:
ConnectionString6 %>"
SelectCommand='<%# "SELECT DISTINCT OptionValue.Name,
OptionValue.Id FROM CombinationDetail
INNER JOIN OptionValue
ON CombinationDetail.OptionValueId = OptionValue.Id
WHERE (OptionValue.OptionId =" +
Eval("Id") + ")" %>'>
</asp:SqlDataSource>
<br />
</ContentTemplate>
</asp:UpdatePanel>
</ItemTemplate>
</asp:Repeater>
</ContentTemplate>
</asp:UpdatePanel>
Many thanks for any help :)
This is a real-world use case. I have a page with Repeaters, Ajax Accordions inside of other Accordions, Update Panels inside other Update panels, you name it. The page works great, except when I want to update one of the Accordion panels with my RadioButtonList (RBL). Even with the RBL inside an update panel, it causes a postback of the entire page. I tried everything. I finally realized it wasn't me when I noticed my buttons would work just fine. I figure it must be a bug in either the framework or the Ajax Control Toolkit. I did find people reference this link all over the web (http://blog.smarx.com/posts/the-case-of-the-radiobuttonlist-half-trigger.aspx), but this link from 2007 is dead now and probably no longer applicable, so that's no help.
What I ended up doing was going with what works - that submit button. All I did was add an onclick attribute to the RBL to call a hidden button. Now you don't want to set the button to Visible=false because then the button won't appear in the generated markup. Instead, set the button's style to display:none; so that no one will see this hack, because yes, that's what this workaround is - it's a hack, but simple and just as effective as what you'd expect. Don't forget to remove the Autopostback="True" from your RBL.
CAVEAT: Because I'm using a hacked button for the onclick event, it's possible for the user to click in the area of the RBL, but not actually select an item. When this happens, our onclick triggers an AsyncPostBack and the codebehind logic will be processed, so please keep that in mind. To give you an idea of what I mean: all the Page_Load() events will be called, but rbl_Questions_SelectedIndexChanged() won't be if they happen to click in the area of the RBL without actually selecting an item. For my purposes this causes no issues in my logic and has no effect on the user.
Here's the Code:
Somewhere In the .Aspx Page:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:RadioButtonList ID="rbl_Questions" runat="server"
OnSelectedIndexChanged="rbl_Questions_SelectedIndexChanged">
</asp:RadioButtonList>
<asp:Button ID="btn_rbl_Questions" runat="server" style="display:none;"/>
<asp:Label ID="lbl_Result" runat="server" Text="" Visible="false">
</asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
In the Page_Load() event:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
//Instead of using the AutoPostback of the RBL, use this instead.
rbl_Questions.Attributes.Add("onclick",
"document.getElementById('"
+ btn_rbl_Questions.ClientID
+ "').click();");
//Bind your RBL to a DataSource, add items programmatically,
// or add them in the aspx markup.
}
}
In the rbl_Questions_SelectedIndexChanged() event:
protected void rbl_Questions_SelectedIndexChanged(object sender, EventArgs e)
{
//Your code here.
//My code unhid the lbl_Result control and set its text value.
}
Update 05/24/2011
The above "hack" is no longer necessary (I am leaving it above since this was marked as the answer by the author). I have found the best way to do this, thanks to this SO Answer:
Updatepanel gives full postback instead of asyncpostback
The code is much simpler now, just remove what I put in the Page_Load() method and remove the Button I used in the Aspx page and add ClientIDMode="AutoID" and AutoPostBack="True" to the control you want the UpdatePanel to capture.
Somewhere In the .Aspx Page:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:RadioButtonList ID="rbl_Questions" runat="server"
ClientIDMode="AutoID" AutoPostBack="true"
OnSelectedIndexChanged="rbl_Questions_SelectedIndexChanged">
</asp:RadioButtonList>
<asp:Label ID="lbl_Result" runat="server" Text="" Visible="false">
</asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
MS changed how ClientID's are generated in .net 4.0 from "AutoID" to "Predictable" and I guess the ScriptManager or UpdatePanel's weren't updated correctly to use it. I can't find documentation on why that is anywhere or if it was left that way by design.
I seriously don't miss winforms.
Try this:
<asp:UpdatePanel runat="server" UpdateMode="Conditional" ID="pnlA">
You'll also need to setup
<Triggers>
//radio buttons
</Triggers>
Not sure how you'll do that since it's a dynamically built list.

ASP.NET - Using checkbox from the calender control

I am implementing a leave system using the calender control. Something like below :-
Following is the markup :-
<asp:Calendar ID="Calendar1" runat="server" ondayrender="Calendar1_DayRender"
ShowGridLines="True">
</asp:Calendar>
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem Value="vacation" Text="Vacation" />
<asp:ListItem Value="sick" Text="Sick" />
<asp:ListItem Value="training" Text="Training" />
</asp:DropDownList>
<asp:Button ID="Button1" runat="server" Text="Save" onclick="Button1_Click" />
Following is the code-behind :-
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
if (!e.Day.IsOtherMonth && !e.Day.IsWeekend)
{
CheckBoxList list = new CheckBoxList();
list.Items.Add(new ListItem("Half day"));
list.Items.Add(new ListItem("Full day"));
e.Cell.Controls.Add(list);
}
}
However, I am not able to access the the checkbox values neither in the button_click event nor in the DayRender event? Could anybody help? Is there a better way to implement this?
Because you are not binding any event handler to the CheckBox's also you haven't shown us the java-script you are using for Button click so I assume that you instead wanted to run a Server side code instead of Client side java-script. So instead of using OnClick attribute which is for client event script you should use Click Event which is for server side code

Using code nuggets for setting controls properties

Why cant i use code nuggets to set a control property??For example a validationgroup of a button or the text property of a label.
<asp:Button ID="btn" runat="server" Text="test" ValidationGroup='<% =TestValidate %>'
<asp:Label ID="lbl" runat="server" Text='<% =Test %>' />
Is there any way to set a controls properties without using codebehind?
You could use data binding:
<asp:Label ID="lbl" runat="server" Text='<%# "Hello World" %>' />
provided that you call DataBind in code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataBind();
}
}
<%=SomeVar %> uses late binding which behaves like a Response.Write (in Page.PreRender, if I remember correctly). Hence it will not be utilized by the server controls like the way you wanted it. Unless you use code-behind or inline-code-behind to perform binding.

Resources