[Last Call] Learn how to a build a cloud-first strategyRegister Now


Need to use a cookie with MVC3

Posted on 2011-10-08
Medium Priority
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
  • 3
  • 2
LVL 16

Expert Comment

ID: 36943330
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

ID: 36944166
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

ToddBeaulieu earned 2000 total points
ID: 36944217
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

ID: 36946141

Author Comment

ID: 36946223

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

JavaScript can be used in a browser to change parts of a webpage dynamically. It begins with the following pattern: If condition W is true, do thing X to target Y after event Z. Below are some tips and tricks to help you get started with JavaScript …
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
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…
Suggested Courses
Course of the Month18 days, 14 hours left to enroll

834 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