asp.net - 如何设置asp :DropDownList SelectedValue to a Session Variable?

标签 asp.net session drop-down-menu session-variables sqldatasource

有几篇文章描述了如何在代码后面执行此操作:

是否可以将下拉列表的值设置为aspx页面上的 session 变量?

我正在使用 SqlDataSource 填充下拉列表,因此如果可以避免的话,不希望在后面添加代码。

<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" />

session (“ID”)设置为加载时选定的值?


下拉列表已从 sqldatasource 填充。我只想设置页面加载时的初始值。

最佳答案

您需要服务器端代码才能使用 session 。以下代码不需要文件后面的代码,但脚本内的代码将在服务器端运行。

<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>

注意:确保 DropDownList AutoPostBack="True"

关于asp.net - 如何设置asp :DropDownList SelectedValue to a Session Variable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21631247/

相关文章:

CSS 菜单在 IE8 中不起作用

asp.net - 如何使用 CSS 设置 asp.net 菜单的样式

asp.net - Visual Studio - 调试给出错误 0x800700b7

asp.net - 您让 Sitecore(或其他 CMS)管理多少?

python - 带有网络服务器的 Flask 会中断所有 session 吗?

jquery - 使用 jQuery 获取选择框中先前选定的项目

c# - ASP.NET 执行超时不抛出

java - 使用 Java 客户端实现 Spring Security

php - PHP函数中的 session

actionscript-3 - 字符串的长度(以像素为单位)