Introduction
In web applications, sometimes we need to store user information temporarily. For example:
User login information
Shopping cart items
User preferences
Website language settings
ASP.NET MVC provides two common ways to store this information:
Session
Cookies
Many beginners get confused about when to use Session and when to use Cookies.
In this article, we will learn:
What Session is
What Cookies are
The difference between Session and Cookies
Simple examples with code
What is Session?
A Session stores user data on the server side.
When a user visits a website, the server creates a unique Session ID for that user. The session keeps user information during the browsing session.
Example:
If a user logs into a website, we can store the username in Session.
Session Example in ASP.NET MVC
Store Data in Session
public ActionResult Login()
{
Session["Username"] = "Abhay";
return View();
}Retrieve Session Data
public ActionResult Dashboard()
{
string user = Session["Username"].ToString();
ViewBag.User = user;
return View();
}Display Data in View
<h2>Welcome @ViewBag.User</h2>What is this?
Output:
Welcome AbhayHere the username is stored in the server session.
What are Cookies?
Cookies store user information in the user's browser.
Cookies remain stored even after the browser is closed (if expiry is set).
Example uses:
Remember login
Save language preference
Save theme settings
Cookies Example in ASP.NET MVC
Create Cookie
public ActionResult SetCookie()
{
HttpCookie cookie = new HttpCookie("UserName");
cookie.Value = "Abhay";
cookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(cookie);
return View();
}Read Cookie
public ActionResult GetCookie()
{
string name = Request.Cookies["UserName"].Value;
ViewBag.Name = name;
return View();
}Display in View
<h2>User Name: @ViewBag.Name</h2>What is this?
Output:
User Name: Abhay
Join the conversation! Your thoughts help the community grow.