2017-08-11 42 views
0

是否可以在回發之前從下拉列表中設置會話變量?回發之前從下拉列表中設置會話變量?

我有3個DropDownLists。第一個OnSelectedIndexChanges填充第二個,第二個填充第三個。第三個DropDownList將autopostback設置爲false,因爲基於第二個下拉列表選擇,第三個下拉列表可能只有一個值可供選擇。似乎沒有用,只能讓用戶從一個選項中進行選擇。

如何設置從第三下拉列表會話變量沒有回傳?

+0

當你從第二個下拉菜單回來,你檢查任何數據源正在駕駛的第三個下拉列表,並設置你的會話變量。 –

+0

你試過什麼? – AsifAli72090

+0

如果您的第三個下拉菜單中只有一個項目,則在第二個下拉菜單中選中的索引更改事件會話。如果您在下拉菜單中有多個項目,則在html側創建onchage事件並啓用會話啓用的webmethod以在會話中添加所選項目。如果你確定只有一個項目會在第三個下拉菜單中出現,那麼你可以在第二個下拉菜單中設置選定的索引改變,否則你必須去服務器端設置會話。 – Yogesh

回答

0

爲了實現您的要求,通常我們使用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"]