D-W
D-W

Reputation: 5341

MVC4 Get Cookie Value

In my controller im setting a simple cookie value

var menuCookie = new HttpCookie("menuC");
            menuCookie.Value= account.MinimisedMenu.ToString();
            menuCookie.Expires = DateTime.Now.AddHours(24);
            Response.Cookies.Add(menuCookie);

then on the page I need a bool value

$(document).ready(function () {
  m [email protected]["menuC"].Value;

        if (m) {
            alert(m);
        };
});

But Im getting an "Uncaught ReferenceError: False is not defined"

This what the browser renders

  var m = false;
        m =False; //<--doe not like

is it because its uppercase?, what do I need to do to fix?

Upvotes: 0

Views: 1343

Answers (2)

David Godwin
David Godwin

Reputation: 731

Depending on your exact requirements, also remember that it can sometimes be easier to use razor to alter your JS so the client browser doesn't have to think as much (using cookies to communicate from controller to view is obviously inefficient). Here's an example:

$(document).ready(function () {
    @if (MyViewModel.ShowMenuC)
    {
        <text>
        alert("menu c jquery stuff here!");
        </text>
    }
});

Upvotes: 2

Rhumborl
Rhumborl

Reputation: 16609

Yes it is because it is in upper case, so JavaScript doesn't understand it. So you need to set it to lower case somewhere:

Option 1: on the page

$(document).ready(function () {
    m = @Request.Cookies["menuC"].Value.ToLower();
    if (m) {
        alert(m);
    };
});

Option 2: in the cookie, which is probably a better choice (write once, read many)

menuCookie.Value = account.MinimisedMenu.ToString().ToLower();

Upvotes: 3

Related Questions