Saturday 29 April 2017

Session And View State In ASP .NET

Session And View State :
1. View state values are accessible with the same page
2. Session variables can be accessed across pages.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Part1.aspx.cs" Inherits="SessionViewState.Part1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">   
<title></title>
</head>
<body>   
<form id="form1" runat="server">   
<div>       
<asp:Button ID="btnCount" runat="server" Text="count" OnClick="btnCount_Click" />        <asp:Button ID="btnCountPart2" runat="server" Text="Count2" OnClick="btnCountPart2_Click" />   
</div> 
  </form>
</body>
</html> 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SessionViewState
{
    public partial class Part1 : System.Web.UI.Page    {
        private int Count;
        protected void Page_Load(object sender, EventArgs e)
        {
            Count = Convert.ToInt16(ViewState["MyCount"]);
            //Count = Convert.ToInt16(Session["MyCount"]);        }

        protected void btnCount_Click(object sender, EventArgs e)
        {
            Count++;
            ViewState["MyCount"] = Count;
           // Session["MyCount"] = Count;            Response.Write(Count);
        }

        protected void btnCountPart2_Click(object sender, EventArgs e)
        {
            Response.Redirect("Part2.aspx");
        }
    }
}


3. View state information is stored in hidden fields in client
        side(inspect or view the element)
4. View state is base 64 encoded so not good  for critical information.























5. Session data is stored on the server and keys are stored in cookies files.
6. If cookie is disabled then session id key passed via query string.




















8. As data is stored on server critical information can be stored.
9. View state client side and session is server side.


Difference between Temp Data,View Data,View Bag :

View Data :
Helps to maintain data when you  move from Controller to View.
In view data type casting is possible.
View data array notation.

View Bag :
It is dynamic wrapper around view data.it also move data from Controller to View.
In view bag no need for type casting.
View bag dot notation.


Temp Data :
Helps to maintain data when you move from one controller to another controller or from one action to another action.

No comments:

Post a Comment