State Management In ASP.NET MVC
- Hidden
Field
- Cookies
- Query
String
- ViewData
- ViewBag
- TempData
- @Html.HiddenFor(x=>x.Id)
- <input data-val="true" data-val-number="The field Id must be a number." data-val-required="The Id field is required." id="Id" name="Id" type="hidden" value="1001" />
- HttpCookie cookie = new HttpCookie("TestCookie");
- cookie.Value = "This is test cookie";
- this.ControllerContext.HttpContext.Response.Cookies.Add(cookie);
- if (this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("TestCookie"))
- {
- HttpCookie cookie = this.ControllerContext.HttpContext.Request.Cookies["TestCookie"];
-
- ViewBag.CookieMessage = cookie.Value;
- }
There are
two type of Cookies in Asp.Net:
1.
Persistent Cookies:
·
Persistent
Cookies are Permanent Cookies stored as a text file in the hard disk of the
computer.
·
Persistent
cookie also known as tracking cookie, because while setting this type of
cookies, you can set a very long expiry date like one year and more.
For example: when you use Gmail, and click on "remember
me" checkbox, that time a cookie stored in your computer which is used
next time again you access Gmail from same computer.
2.
Non-Persistent Cookies:
·
Non-Persistent
cookies are temporary. They are also called browser memory cookies and
session-based cookies
Add
Remove Cookies in Asp.net MVC
To create cookie, we just need to create a new HttpCookie object in controller action
public ActionResult cookies()
{
// Create the cookie object.
HttpCookie cookie = new HttpCookie("WTR");
cookie["website"] = "WebTrainingRoom"; //
This cookie will remain for one month.
cookie.Expires = DateTime.Now.AddMonths(1);
// Add it to
the current web response.
Response.Cookies.Add(cookie);
return View();
}
Properties
in HttpCookies Class:
Name: Contains the name of the Key.
Domain: Using these properties we can set the
domain of the cookie.
Expires: This property sets the Expiration time
of the cookies.
HasKeys: If the cookies have a subkey then it
returns True.
Value: Contains the value of the cookies.
Secured: If the cookies are to be passed in a
secure connection then it only returns True.
Path: Contains the Virtual Path to be
submitted with the Cookies.
Just two simple things Request.Cookies
(to retrive) and Response.Cookies (to add)
Here is
how we can retrive Cookies information in in Asp.net MVC action
HttpCookie cookieObj = Request.Cookies["WTR"];
string _websiteValue = cookieObj["website"];
We all can retrieve all cookies in current httpContext, below code demonstrate
how we can retrieve all values from cookie of current httpContext.
HttpCookieCollection _cookiees =
HttpContext.Current.Request.Cookies;
foreach (HttpCookie cookie in _cookiees)
{
// get the domain name who has set the cookie
string _domainname = cookie.Domain;
//retrive single value
string _value = cookie.Value;
// get multiple value from one cookie value
NameValueCollection _values = cookie.Values;
// get the date when expire
DateTime _expirydate = cookie.Expires;
}
What are
Third-party cookies?
Third party cookie means cookies being set by the
different domain, than the current one shown in the address bar.
For example, now you are accessing MakeMyTrip.Com then there
may some cookies will be stored by some adverteiser.Com, then again when you
visit a different site like GoIbibo.Com, some similar advertisement will be
displayed to you using cookies was stored by adverteiser.Com earlier.
So all advertisement you see while browsing your regular site
like Google or Bing, are displayed based on some kind of third party cookies,
that’s the reason you keep seeing similar type of advertisement when you keep
checking different sites.
Cookies
with real time example
So, you may have question like when to create a cookie in your web application and how!
When to create a cookie in your web application that will
depend on type of application you have, if you have a mechanism like user
login, and you want to provide functionality like “remember login” when user
visit your site next time, you can create a persistent cookie on login button
click.
But if you want to create cookie when a user your visit your
website, then use session start
event in global.asax.
You can write like this,
private HttpCookie CreateStudentCookie()
{
HttpCookie wtrCookies = new
HttpCookie("wtr");
wtrCookies.Value = "WebTrainingRoom";
wtrCookies.Expires = DateTime.Now.AddMonths(1);
return wtrCookies;
}
protected void Session_Start(object sender, EventArgs e)
{
CreateStudentCookie();
}
Use
Cookie for Authentication
Here we see another example of how use cookie for authentication.
First we store all user information in
FormsAuthenticationTicket, then Encrypt all values into a string value, finally
store that string into a cookie with FormsCookieName.
User user = new User();
user.id = 1001;
user.username = "someUserName";
string _pipeSeparatedUserData = user.GetUserData();
DateTime expire =
DateTime.Now.AddMinutes(FormsAuthentication.Timeout.TotalMinutes);
FormsAuthenticationTicket ticket = new
FormsAuthenticationTicket(user.id, user.username, DateTime.Now, expire, false,
_pipeSeparatedUserData);
string hashTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName,
hashTicket);
HttpContext.Current.Response.Cookies.Add(cookie);
Now we retrieve all values from cookie object and use for
further authentication.
HttpCookie authCookie =
HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
FormsAuthenticationTicket authTicket =
FormsAuthentication.Decrypt(authCookie.Value);
if (authTicket == null || authTicket.Expired)
return ;
string _name = authTicket.Name;
string _userData = authTicket.UserData;
}
In above example you can see how encrypted values stored in
cookie and the retrieved values from cookie and decrypted for further use.
- public ActionResult Index()
- {
- Employee emp = new Employee()
- {
- Id = 1001,
- Name = "Mukesh Kumar",
- Address = "New Delhi",
- Age = 25
- };
-
- ViewData["Message"] = "This is ViewData";
- ViewData["Emp"] = emp;
-
- return View();
- }
- @{
- ViewBag.Title = "Home Page";
- }
-
- <div class="row">
- <div class="col-md-4">
- <h2>Employee Details</h2>
- <br />
- <p>
- @if(ViewData["Message"] !=null)
- {
- <b>@ViewData["Message"].ToString();</b>
- }
- </p>
- <br />
- @if (ViewData["Emp"] != null)
- {
-
- var emp = (MVCStateManagement.Models.Employee)ViewData["Emp"];
- <table>
- <tr>
- <td>
- Name :
- </td>
- <td>
- @emp.Name
- </td>
- </tr>
- <tr>
- <td>
- Address :
- </td>
- <td>
- @emp.Address
- </td>
- </tr>
- <tr>
- <td>
- Age :
- </td>
- <td>
- @emp.Age
- </td>
- </tr>
- </table>
- }
- </div>
- </div>
- public ActionResult Index()
- {
- Employee emp = new Employee()
- {
- Id = 1001,
- Name = "Mukesh Kumar",
- Address = "New Delhi",
- Age = 25
- };
-
- ViewBag.Message = "This is ViewBag";
- ViewBag.Emp = emp;
-
- return View();
- }
- @{
- ViewBag.Title = "Home Page";
- }
-
- <div class="row">
- <div class="col-md-4">
- <h2>Employee Details</h2>
- <br />
- <p>
-
- <b>@ViewBag.Message</b>
-
- </p>
- <br />
- @{
- var emp = ViewBag.Emp;
- <table>
- <tr>
- <td>
- Name :
- </td>
- <td>
- @emp.Name
- </td>
- </tr>
- <tr>
- <td>
- Address :
- </td>
- <td>
- @emp.Address
- </td>
- </tr>
- <tr>
- <td>
- Age :
- </td>
- <td>
- @emp.Age
- </td>
- </tr>
- </table>
- }
- </div>
- </div>
Note
- If you are using ViewData that is not defined on Controller, then it will throw an error; but with ViewBag, it will not.
- Do not use ViewBag and ViewData with the same name, otherwise, only one message will display. See the following code in the controller is using both ViewData and ViewBag with same name “Message”.
- public ActionResult Index()
- {
- Employee emp = new Employee() { Id = 1001, Name = "Mukesh Kumar", Address = "New Delhi", Age = 25 };
-
- //Setting the TempData
- TempData["Emp"] = emp;
- return RedirectToAction("Index1");
- }
- public ActionResult Index1()
- {
- //Not reading TempData
- return RedirectToAction("Index2");
- }
- public ActionResult Index2()
- {
- //Not reading TempData
- return RedirectToAction("About");
- }
- public ActionResult About()
- {
- //Not reading TempData
- return View();
- }
-
- public ActionResult Contact()
- {
- //Data will available here because we have not read data yet
- var tempEmpData = TempData["Emp"];
- return View();
- }
- @{
- ViewBag.Title = "About";
- }
- <h2>About Page</h2>
- <br />
- @{
- var data = (MVCStateManagement.Models.Employee)TempData["Emp"];
- }
- public ActionResult Contact()
- {
- //Data will not available here because already read on About page
- var tempEmpData = TempData["Emp"];
- return View();
- }
- @{
- var data = (MVCStateManagement.Models.Employee)TempData["Emp"];
- TempData.Keep();
- }
- public ActionResult Contact()
- {
- //TempData will available here because we have keep on about page
- var tempEmpData = TempData["Emp"];
- return View();
- }
- @{
- var data = (MVCStateManagement.Models.Employee)TempData.Peek("Emp");
- }
- public ActionResult Contact()
- {
- //TempData will available because we have already keep data using Peek() method.
- var tempEmpData = TempData["Emp"];
- return View();
- }
Comments
Post a Comment