MVC 2 - Cookies Not Saving
I have a simple application where I am trying to save a value into my cookie but it is not saving. Below is the code and I do not know where the problem is.
Code below is from the controller:
public ActionResult Index()
{
string cookieValue = "";
if (Request.Cookies["my_cookie"] != null)
{
cookieValue = Request.Cookies["my_cookie"].Value;
}
if (! string.IsNullOrEmpty(cookieValue ))
{
ViewData["ck"] = cookieValue;
}
else { ViewData["ck"] = "no cookie value"; }
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SaveCookieData(FormCollection formValue)
{
HttpCookie myCookie = new HttpCookie("my_cookie", formValue["cookieTXT"].ToString());
Response.Cookies.Add(myCookie);
}
This code is from the view:
<% using (Html.BeginForm("SaveCookieData", "Home", FormMethod.Post)) { %>
<textarea id="cookieTXT" rows="2" cols="20" runat="server" />
<input id="submitBTN"开发者_如何学运维 type="submit" value="Done" runat="server" />
<% } %>
<% if (ViewData["ck"] != null) { %>
<p>Hello Cookie: <%= ViewData["ck"]%></p>
<% } %>
From what it looks like is my form submitted data for cookieTXT is empty because the value for formValue["cookieTXT"] is blank. I can not figure it out why?
Thanks for the help.
First: Try using
Response.SetCookie(myCookie);
Second: Have you tried looking at the cookie saved in the browser? I use Google Chrome to see the cookies that are being read by the browser. You can also use fiddler to see the Set-Cookie: in the response to see if it is responding correctly. Also, make sure the domain setting the cookie matches the domain that is reading the cookie.
Ex. Domain = domain.com
Your site must have domain.com in the URL to read the cookie.
精彩评论