我想在触发下拉列表更改事件后更改Cookie的值。
我在基本控制器上有一个带有以下代码的mvc应用程序:
public class CustomController : Controller
{
HttpCookie mYcookie = new HttpCookie("trycookie");
HttpCookie cookieCounter = new HttpCookie("cookieCounter");
protected override void OnActionExecuted()
{
if (cookieCounter.Value == null)
{
mYcookie.Value = "tryvalue";
// do something here //
}
}
}
它的作用是在应用程序运行后创建cookie的实例。然后我有一个jquery来操纵cookie:
$.cookie("mYcookie", "tryvaluehere");
$.cookie("cookieCounter", "tryvaluehereagain");
我的问题在这里每当我调试我的c#代码时,我的cookie的值都是“”。但每当我试图在相同的jquery代码上提醒cookie时,我得到了我想要的值
alert($.cookie("mYcookie"));
即使我在我的方法之外声明它们,我的HttpCookie
实例是否会再次创建?任何建议都将很乐意受到赞赏。提前谢谢!
答案 0 :(得分:1)
我所做的是从请求中创建cookie的实例。如果请求为null,则将该cookie创建为新cookie。
public class CustomController : Controller
{
HttpCookie mYcookie = this.Request.Cookies["trycookie"];
HttpCookie cookieCounter = this.Request.Cookies["trycookie"];
protected override void OnActionExecuted()
{
if (cookieCounter == null)
{
mYcookie = new HttpCookie("somenamehere");
}
else
{
// do something here //
}
}
}
答案 1 :(得分:0)
您应该从请求中读取cookie:
public class CustomController : Controller
{
protected override void OnActionExecuted()
{
HttpCookie myCookie = this.Request.Cookies["trycookie"];
HttpCookie cookieCounter = this.Request.Cookies["cookieCounter"];
if (cookieCounter != null)
{
// do something here //
}
}
}
或者如果你想设置一个cookie,那么创建一个新的cookie实例并将其添加到响应中:
HttpCookie cookie = new HttpCookie("name", "some value");
this.Response.Cookies.Add(cookie);