0

一旦触发下拉更改事件,我想更改 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即使我在我的方法之外声明它们,是否会再次创建我的实例?任何建议将不胜感激。提前致谢!

4

2 回答 2

1

我所做的是从请求中创建一个 cookie 实例。如果请求为空,则将该 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 //
        }
    }
}
于 2013-09-05T01:58:50.887 回答
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);
于 2013-09-04T07:14:55.727 回答