Session In ASP.NET MVC

As we all know that HTTP Protocol is a stateless protocol which means that it can’t store the data of the previous page. So to maintain the state we use Session and Cookie.

What is Session?

The session is a small piece of information stored on the server side. The session is very useful for any web application. Using the session variable we can pass data from controller to view and model to controller.

Let us understand this by an example.

First, create a model class as Users.

public class Users
{
        public String Username{ get; set; }
        public String Password{ get; set;
}

Now code on the controller side to process the session data.

public ActionResult Index()
{
       Users user = new Users();   
       user.Username = "Faisal";  
       user.Password = "123456";   
       Session["User"] = user;
       return View();
}

Now we have stored all the information of the user in Session. Now we can access the Session on the View side.

@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <title>Index</title>
</head>
<body>
    <div>
        @{
            var info = (Demo.Models.Users) Session["User"];
        }
       
        Username is :- @info.Username;
        <br />
       
        Password is :-@info.Password;
    </div>
</body>
</html>

 

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories