Question

I want to seamlessly keep state for all the anonymous visitors of the web site. For example to show hint only on the first visit and initially prevent "vote" button from appearing via-cookie analyzing java-script on the client (of cause with the second-level ip-based filtering on the server side).

How can I manage these cookies in the client browser. Ideally I'd like to use them as a dictionary that I can read and write from both on the server and on the client. If this is all a basic stuff, please just show how I can assign "hasVoted" bool value to the cookie of the user and read it off on the client and on server.

If anything is fundamentally wrong with my idea, please let me know =)

Was it helpful?

Solution

After they vote (which I assume happens in a POST), you'll want to set the cookie:

[HttpPost]
public ActionResult Vote()
{
    HttpCookie hasVoted = new HttpCookie("hasVoted", true);
    Request.Cookies.Add(hasVoted);

    return RedirectToAction("Index");
}

And get it like this:

[HttpGet]
public ActionResult Index()
{
    bool hasVoted = Request.Cookies["hasVoted"].Value;        

    return View();
}

If I was doing this I would take that hasVoted bool, wack it in a ViewModel and set the visibility of the button based on that value in your .aspx page. If you really want to though, you can read and write to cookies using javascript:

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}

Check this out http://www.quirksmode.org/js/cookies.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top