简体   繁体   中英

Keep state info for anonymous user in ASP.NET MVC application

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 =)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM