I want to register the parameter of a few pages in my web site using cookie. I tried the below code but not like what I want :
public ActionResult Index(int? dep, int? cat) { ...... string theDept = Request.QueryString["dep"]; HttpCookie cookie = new HttpCookie("search"); cookie.Values["dep_name"] = theDept; cookie.Expires = DateTime.Now.AddDays(1); Response.Cookies.Add(cookie); return View(); }
I read it in site.master :
<% HttpCookie cookie = Request.Cookies["search"] ; if ((cookie != null) && (cookie.Value != "")) { Response.Write(cookie.Values["dep_name"].ToString() + "---" + cookie.Values["cat_name"].ToString() + "---" + cookie.Values["brand"].ToString()); } %>
Problem: When I click to another page that Request.QueryString["dep"]
is null, the cookie that I display is null to.
How to store it in the cookie without losing while we not yet clear the cookie?
In ASP.Net MVC application, a Cookie is created by sending the Cookie to Browser through Response collection (Response. Cookies) while the Cookie is accessed (read) from the Browser using the Request collection (Request. Cookies).
Cookies is a small piece of information stored on the client machine. This file is located on client machines "C:\Document and Settings\Currently_Login user\Cookie" path. Its is used to store user preference information like Username, Password,City and PhoneNo etc on client machines.
In ASP.NET MVC, there is an OutputCache filter attribute that you can apply and this is the same concept as output caching in web forms. The output cache enables you to cache the content returned by a controller action. Output caching basically allows you to store the output of a particular controller in the memory.
Yes, by default ASP.NET Session use cookies.
I m not sure I understand if this is a question about how to properly send cookies to the client or some bug with your querystring params. So I ll post the proper way of sending cookies and feel free to correct me if I misunderstood.
In any case though, I believe this:
HttpCookie cookie = new HttpCookie("search");
will reset the search cookie
To get a cookie:
HttpCookie cookie = HttpContext.Request.Cookies.Get("some_cookie_name");
To check for a cookie's existence:
HttpContext.Request.Cookies["some_cookie_name"] != null
To save a cookie:
HttpCookie cookie = new HttpCookie("some_cookie_name"); HttpContext.Response.Cookies.Remove("some_cookie_name"); HttpContext.Response.SetCookie(cookie );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With