2

I had set a cookie in javascript some thing like this

   function setCookie(c_name,value,exdays)
    {
       var exdate=new Date();
       exdate.setDate(exdate.getDate() + exdays);
       var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
       document.cookie = c_name + "=" + c_value;
    }

var  loginval = slmgusername=swetha.p + slmguserpassword = 12345678;
 setCookie("slmgusercredentails", loginval, 100);

And i controller i am getting values in my cookie like this

 HttpContext.Request.Cookies["slmgusercredentials"].Values = {slmgusername%253Dswetha.p%2526slmguserpassword%253D12345678}

when i am trying to get the username from this some thing like

 UserName = HttpContext.Request.Cookies["slmgusercredentials"].Values["slmgusername"].

I cant able to get the UserName. As i think so the values are in javscript coding format. How to get the username... can any one help me to find the solution...

1
  • Please tag this question with your back-end framework (ASP?). It helps to mention it explicitly in the question text, too. Commented May 7, 2012 at 14:53

2 Answers 2

5

This should do the trick!

 function ReadCookie()
    {
       var allcookies = document.cookie;
       alert("All Cookies : " + allcookies );

       // Get all the cookies pairs in an array
       cookiearray  = allcookies.split(';');

       // Now take key value pair out of this array
       for(var i=0; i<cookiearray.length; i++){
          name = cookiearray[i].split('=')[0];
          value = cookiearray[i].split('=')[1];
          alert("Key is : " + name + " and Value is : " + value);
       }
    }
Sign up to request clarification or add additional context in comments.

2 Comments

Doesn't work for key=value;expires=Thu, 01 Jan 1970 00:00:00 GMT. expires considered as another cookie
@dr.dimitru Of course it works, he splits key-values pairs on line 7
1

Solves the expired problem from accepted answer.

function readKeyValuesFromCookie(){
    return document.cookie
        .split( ';' )
        .map( pair => pair.split( '=' ) )
        .filter( pair => pair.length == 2 )
        .map( pair => [ pair[0].trim(), pair[1].trim() ] )
        .filter( pair => pair[0] != 'expires' )
    ;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.