tau
tau

Reputation: 288

Access cookie from Client Side

I have set a cookie on the controller:

 HttpCookie loggedIn = new HttpCookie("LoggedIn", "true");
 Request.Cookies.Add(loggedIn);

I am trying to access this on document ready?

$( document ).ready(function() {
   if ('@Request.Cookies["LoggedIn"]' != null) {
        var loggedIn = '@Request.Cookies["LoggedIn"].Value';
        console.log("Logged In " + loggedIn);
    }

});

This keeps coming through as null?

Any ideas?

Upvotes: 0

Views: 2670

Answers (1)

Ferruccio
Ferruccio

Reputation: 100658

You're not actually accessing the cookie from the client-side JavaScript. Even though you're sending the cookie back to the browser, your code is ignoring that cookie and trying to access it via a Razor expansion. I guess that could work, but it seems like a roundabout way to do it.

You can access cookies from JavaScript though the document.cookie property, which is a ; delimited list of cookies.

Since you're using jQuery, a simpler way is to use the jquery.cookie plugin.

var loggedIn = $.cookie('LoggedIn');

Update: I just realized you're setting the cookie in the request. You should be setting it in the response:

Response.SetCookie(loggedIn);

Upvotes: 2

Related Questions