Gerald
Gerald

Reputation: 1083

jQuery setting value of a session

I want to change the value of a cookie once a dropdown change event is triggered.

I have an mvc application with the following code on base controller:

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 //
        }
    }
}

What it do is create an instance of a cookie once the application run. Then I have a jquery to manipulate the cookie:

$.cookie("mYcookie", "tryvaluehere");
$.cookie("cookieCounter", "tryvaluehereagain");

My problem here whenever I debug on my c# code, the value of my cookies are " ". But whenever I tried to alert the cookie on that same jquery code, I get the value I wanted

alert($.cookie("mYcookie"));

Is my HttpCookie instance being created again even if I declare them outside my method? Any suggestions will gladly be appreciated. Thanks in advance!

Upvotes: 0

Views: 488

Answers (2)

Gerald
Gerald

Reputation: 1083

What I did is create an instance of the cookie from the request. If the request is null, create that cookie as a new 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 //
        }
    }
}

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1039498

You should read the cookie from the request:

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 //
        }
    }
}

or if you want to set a cookie then create a new instance of the cookie and add it to the response:

HttpCookie cookie = new HttpCookie("name", "some value");
this.Response.Cookies.Add(cookie);

Upvotes: 0

Related Questions