Tuesday, December 20, 2011

Session in asp.net

Server Side State Management
( Session,Application,Profile Property)

For Application: Click to View Example

For Profile Propery: Click to View Example

Session:


ASP.NET allows you to save values by using session state — which is an instance of the HttpSessionState class — for each active Web-application session


Session state is similar to application state, except that it is scoped to the current browser session. If different users are using your application, each user session will have a different session state. In addition, if a user leaves your application and then returns later, the second user session will have a different session state from the first.



Example

in .aspx page

Session.aspx


<form id="form1" runat="server">
    <asp:DropDownList runat="server" id="ColorSelector" autopostback="true" onselectedindexchanged="ColorSelector_IndexChanged">
        <asp:ListItem value="White" selected="True">Select color...</asp:ListItem>
        <asp:ListItem value="Red">Red</asp:ListItem>
        <asp:ListItem value="Green">Green</asp:ListItem>
        <asp:Button Id="Button1" Text="Click" runat="Server" />
    </asp:DropDownList>
    </form>


in .cs page



 protected void Page_Load(object sender, EventArgs e)
    {
       
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
       Session["Color"]=ColorSelector.SelectedValue.toString();                                Response.Redirect("Sessioncatch.aspx");
    }



in .aspx page

Sessioncatch.aspx
<form id="form1" runat="server">
   
        <asp:Label Id="Label1" runat="Server" />
   
    </form>

in .cs page

 protected void Page_Load(object sender, EventArgs e)
    {
       if(Session["Color"]<>"")                                                                {                                                                                               Label1.Text=Session["Color"].toString();                                        }                                                                                                                                                
    }
   

To Destroy Session



  • "Session.Abandon(): destroys the session
  • "Session.Clear(): just removes all values
  • To clear particular session, i suggest to write            
   Example
                Session["Color"]=" ";  // It will clear particular session











No comments:

Post a Comment