Get and Set Cookie - Javascript

Get and Set Cookie - Javascript

code snippet

javascript
function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) {
                c_end = document.cookie.length;
            }
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}

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

code snippet

c#
private HttpCookie GetCookie(string cookieName)
{
    HttpCookie cookie = new HttpCookie(cookieName);
    if (Request.Cookies[cookieName] == null)
    {
        cookie = new HttpCookie(cookieName);
        cookie["fieldname"] = "1";
    }
    else
    {
        cookie = Request.Cookies[cookieName];
    }
    return cookie;
}

private HttpCookie SetCookie(string strKey, string strValue, string cookieName)
{
    HttpCookie cookie = new HttpCookie(cookieName);
    if (Request.Cookies[cookieName] == null)
    {
        cookie = new HttpCookie(cookieName);
        cookie[strKey] = strValue;
    }
    else
    {
        cookie = Request.Cookies[cookieName];
        cookie[strKey] = strValue;
    }
    System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
    return cookie;
}

"What we think, we become"

Contact me!

Have questions? Feel free to use the form or send me an email with any questions.

I will be responsive to your requests and your questions.