Set Session With Several Ways
First:how to read session
1, Session["key"].ToString()
2, <%=Session["key"]%>
- ASPX.CS
It's easy as you know, here I'll foucus on "ASPX". - ASPX:
Solution 1: __doPostBack
Here the initialize is necessary
1<script runat="server">
2 private void Page_Load(object sender, System.EventArgs e)
3 {
4 // Insure that the __doPostBack() JavaScript method is created
5 this.ClientScript.GetPostBackEventReference(this, string.Empty);
6
7 if (this.IsPostBack)
8 {
9 string eventTarget = (this.Request["__EVENTTARGET"] == null) ? string.Empty : this.Request["__EVENTTARGET"];
10 string eventArgument = (this.Request["__EVENTARGUMENT"] == null) ? string.Empty : this.Request["__EVENTARGUMENT"];
11
12 if (eventTarget == "SetSessionPostBack")
13 this.Session["SessionValue"] = eventArgument;
14 }
15 else
16 {
17 this.Session["SessionValue"] = "Original value";
18 }
19 //show session value
20 this.Response.Write("SessionValue: " + this.Session["SessionValue"].ToString() + "<br>");
21 }
22</script>
2 private void Page_Load(object sender, System.EventArgs e)
3 {
4 // Insure that the __doPostBack() JavaScript method is created
5 this.ClientScript.GetPostBackEventReference(this, string.Empty);
6
7 if (this.IsPostBack)
8 {
9 string eventTarget = (this.Request["__EVENTTARGET"] == null) ? string.Empty : this.Request["__EVENTTARGET"];
10 string eventArgument = (this.Request["__EVENTARGUMENT"] == null) ? string.Empty : this.Request["__EVENTARGUMENT"];
11
12 if (eventTarget == "SetSessionPostBack")
13 this.Session["SessionValue"] = eventArgument;
14 }
15 else
16 {
17 this.Session["SessionValue"] = "Original value";
18 }
19 //show session value
20 this.Response.Write("SessionValue: " + this.Session["SessionValue"].ToString() + "<br>");
21 }
22</script>
And here is the script call __dopostback
1 <script type="text/javascript">
2 function setSessionValue(newValue) {
3 __doPostBack('SetSessionPostBack', newValue);
4 }
5 </script>
2 function setSessionValue(newValue) {
3 __doPostBack('SetSessionPostBack', newValue);
4 }
5 </script>
Here to use function
1 <form id="form1" runat="server">
2 <input id="Button1" type="button" value="button" onclick="setSessionValue('hello');" />
3 </form>
2 <input id="Button1" type="button" value="button" onclick="setSessionValue('hello');" />
3 </form>
Solution 2: AjaxCall
[tbd]