Need to use a cookie with MVC3

Posted on 2011-10-08
Last Modified: 2012-08-13
I have an MVC3 application that uses JavaScript and jQury. I need to use a cookie to record certain values from the last user's session. So I have a few questions:

1) If the data is to be stored in the database, via the Model, is there any reason for a cookie?
2) Can I do 100% of the coe in JavaScript and just leave the data on the user's disk as a cookie with no involvement of the Model?

Please provide the code to do this in JavaScript, in the event I decide to do this client side and not involve the Model.

Question by:newbieweb
    LVL 16

    Expert Comment

    You could do it either way. If you're using a membership provider that handles remembering who the user is (identifying them) then you probably wouldn't need to save the data on the client.

    A recent project needed to remember the user w/o a provider in the mix, so we used a cookie.

    There are tons of examples on writing a cookie from js so I won't bother posting the links. A quick search will get you there.

    You can also write a cookie from the controller like this:

    Response.Cookies["mycookie"].Value = "myvalue";

    Author Comment

    Ok, thanks. It seems that creating a cookie in the controller saves the effort of coding methods in the Model and needing to create a new table, and possible sprocs, right?

    What other code have you got handy for creating, writing to and reading from the cookie, using MVC?
    LVL 16

    Accepted Solution

    Sure, if you're just trying to make things easier on the user (by remembering previous interactions) and it's not mission critical if it's deleted, then a cookie is an easy option.

    You don't have to write it from the server, either. I guess it depends on the situation. Personally, I hate working in js so I'll do everything I can to code in c#.

    So, reading the cookie is automatic. When the use hits your site, the browser automatically imports the cookie and passes the data from it along with the request.

    Actually, this is better code. It shows fetching a cookie and also creating it. We're looking for who the user is. We store a few basic values in the cookie.
    private void SetCookies(string firstname, string lastname, string email, string company)
        HttpCookie userCookie = new HttpCookie("userinfo");
        userCookie["firstname"] = firstname;
        userCookie["lastname"] = lastname;
        userCookie["email"] = email;
        userCookie["company"] = company;
        userCookie.Expires = DateTime.Now.AddYears(1);
    protected Boolean RecognizeUser()
        bool userIsRecognized = true;
        if (Session["userinfo"] == null)
            HttpCookie userCookie = Request.Cookies["userinfo"];
            if (userCookie == null)
                userIsRecognized = false;
                UserInfo newUser = new UserInfo()
                    FirstName = userCookie["firstname"] ?? String.Empty,
                    LastName = userCookie["lastname"] ?? String.Empty,
                    Email = userCookie["email"] ?? String.Empty,
                    Company = userCookie["company"] ?? String.Empty,
                Session["userinfo"] = newUser;
        return userIsRecognized;

    Open in new window


    Author Closing Comment


    Author Comment


    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    What Security Threats Are You Missing?

    Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

    IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
    Article by: DanRollins
    This article describes a JavaScript program that creates a maze made of hexagonal cells.  In Part 2 (, we'll extend the program by adding a depth-…
    The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
    The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

    759 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    12 Experts available now in Live!

    Get 1:1 Help Now