ASP.NET MVC

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>

 

Faisal Pathan

Faisal Pathan is a founder of TheCodeHubs, .NET Project Manager/Team Leader, and C# Corner MVP. He has extensive experience with designing and developing enterprise-scale applications. He has good skills in ASP.NET C#, ASP.NET Core, ASP.NET MVC, AngularJS, Angular, React, NodeJS, Amazon S3, Web API, EPPlus, Amazon MWS, eBay Integration, SQL, Entity Framework, JavaScript, eCommerce Integration like Walmart, Tanga, Newegg, Group-on Store, etc. and Windows services.

Share
Published by
Faisal Pathan

Recent Posts

Testing hk

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Operation

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

TETS NEW

test

3 years ago