有几篇文章描述了如何在代码后面执行此操作:
是否可以将下拉列表的值设置为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/