In this article I will explain with an example, how to use Browser Cookies in ASP.Net MVC Razor.
This article will also explain how to perform operations on Cookies i.e. reading values stored in Cookies, writing (saving) values in Cookies and also removing (deleting) Cookies in ASP.Net MVC Razor.
Controller
The Controller consists of the following four Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
Action method for writing Cookie
When the Write Cookie Button is clicked, WriteCookie Action method is executed which saves the value of the Name TextBox to the Browser Cookie using the object of the HttpCookie class.
Finally, the Cookie is added to the Response.Cookies collection.
Action method for reading Cookie
When the Read Cookie Button is clicked, ReadCookie Action method is executed which fetches the HttpCookie object from the Request.Cookies collection using its Key.
The value read from the Cookie is set in TempData object, which is later displayed using JavaScript Alert Message Box.
Action method for deleting Cookie
When the Remove Cookie Button is clicked, DeleteCookie Action method is executed which fetches the Cookie object from the Request.Cookies collection using its Key.
A Cookie cannot be removed or deleted from Browser, it only can be made expired and hence the Expiry Date of the Cookie is set to a past date and the Cookie is updated back into the Response.Cookies collection.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult WriteCookie()
{
//Create a Cookie with a suitable Key.
HttpCookie nameCookie = new HttpCookie("Name");
//Set the Cookie value.
nameCookie.Values["Name"] = Request.Form["name"];
//Set the Expiry date.
nameCookie.Expires = DateTime.Now.AddDays(30);
//Add the Cookie to Browser.
Response.Cookies.Add(nameCookie);
return RedirectToAction("Index");
}
[HttpPost]
public ActionResult ReadCookie()
{
//Fetch the Cookie using its Key.
HttpCookie nameCookie = Request.Cookies["Name"];
//If Cookie exists fetch its value.
string name = nameCookie != null ? nameCookie.Value.Split('=')[1] : "undefined";
TempData["Message"] = name;
return RedirectToAction("Index");
}
[HttpPost]
public ActionResult DeleteCookie()
{
//Fetch the Cookie using its Key.
HttpCookie nameCookie = Request.Cookies["Name"];
//Set the Expiry date to past date.
nameCookie.Expires = DateTime.Now.AddDays(-1);
//Update the Cookie in Browser.
Response.Cookies.Add(nameCookie);
return RedirectToAction("Index");
}
}
View
The View consists of an HTML Form which has been created using the Html.BeginForm method with the following parameters.
ActionName – Name of the Action. In this case is it set to NULL as the Action method name is set directly on the Submit Button using FormAction attribute.
ControllerName – Name of the Controller. In this case the name is Home.
FormMethod – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
The Form consists of a TextBox and three Submit Buttons i.e. for Reading Cookie, Writing Cookie and Deleting Cookie.
Each Submit Button has been set with a FormAction attribute which specifies the Action method which will be called when the Submit Button is clicked.
When the Read Cookie button is clicked, the value from the TempData object is displayed using JavaScript Alert Message Box.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width"/>
<title>Index</title>
</head>
<body>
@using (Html.BeginForm(null, "Home", FormMethod.Post))
{
<span>Name: </span><input type="text" id="txtName" name="name" /><br/><br/>
<input type="submit" id="btnWrite" formaction="@Url.Action("WriteCookie")" value="Write Cookie"/>
<input type="submit" id="btnRead" formaction="@Url.Action("ReadCookie")" value="Read Cookie"/>
<input type="submit" id="btnDelete" formaction="@Url.Action("DeleteCookie")" value="Remove Cookie"/>
}
@if (TempData["Message"] != null)
{
<script type="text/javascript">
window.onload = function () {
alert('@TempData["Message"]');
};
</script>
}
</body>
</html>
Screenshot
Downloads
Download Code