爲了實現您的要求,通常我們使用AJAX來火服務器端方法來保存會話沒有做全回發。以下代碼作爲快速示例。
<form id="form1" runat="server">
<div>
<asp:DropDownList runat="server" ID="DropDownList_family" AutoPostBack="True" OnSelectedIndexChanged="DropDownList_family_SelectedIndexChanged">
<asp:ListItem>Cat</asp:ListItem>
<asp:ListItem>Dog</asp:ListItem>
<asp:ListItem>Bird</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="DropDownList_species" runat="server"></asp:DropDownList>
<asp:Button ID="Button_showSession" runat="server" Text="ShowSession" OnClick="Button_showSession_Click" />
</div>
</form>
使用的NuGet安裝的jQuery然後
<script type="text/javascript" src="Scripts/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
function SaveSession(input) {
$.ajax({
type: "POST",
url: "Default.aspx/SaveSession",
data: "{'input':'" + input + "'}",
contentType: "application/json; charset=utf-8",
success: function (data) {
},
error: function (data) {
}
});
}
$(function() {
$("#DropDownList_species").on("change", function() {
SaveSession(this.value);
});
});
</script>
終於在代碼隱藏
internal static readonly List<string> _cats = new List<string>() { "American Shorthair", "Siamese", "Chinchilla" };
internal static readonly List<string> _dogs = new List<string>() { "Welsh Corgi", "Beagle", "Husky" };
internal static readonly List<string> _birds = new List<string>() { "Parrot" };
[WebMethod(EnableSession = true)]
public static void SaveSession(string input)
{
HttpContext.Current.Session["YouWant"] = input;
}
protected void DropDownList_family_SelectedIndexChanged(object sender, EventArgs e)
{
List<string> src = new List<string>();
if (DropDownList_family.SelectedValue == "Cat")
{
src = _cats;
}
else if (DropDownList_family.SelectedValue == "Dog")
{
src = _dogs;
}
else if (DropDownList_family.SelectedValue == "Bird")
{
src = _birds;
}
if (!src.Any(str => str == "--Please Select--"))
src.Insert(0, "--Please Select--");
DropDownList_species.DataSource = src;
DropDownList_species.DataBind();
}
protected void Button_showSession_Click(object sender, EventArgs e)
{
Response.Write(Session["YouWant"]);
}
$("#DropDownList_species").on("change"
將觸發功能SaveSession其AJAX調用服務器端方法Default.aspx/SaveSession
那麼它將assgin輸入到Session["YouWant"]
當你從第二個下拉菜單回來,你檢查任何數據源正在駕駛的第三個下拉列表,並設置你的會話變量。 –
你試過什麼? – AsifAli72090
如果您的第三個下拉菜單中只有一個項目,則在第二個下拉菜單中選中的索引更改事件會話。如果您在下拉菜單中有多個項目,則在html側創建onchage事件並啓用會話啓用的webmethod以在會話中添加所選項目。如果你確定只有一個項目會在第三個下拉菜單中出現,那麼你可以在第二個下拉菜單中設置選定的索引改變,否則你必須去服務器端設置會話。 – Yogesh