2

I've made a cookie using asp.net C# code and I want to retrieve its value in javascript

Here's my C# code:

HttpCookie cookie = new HttpCookie("doc1count");
cookie.Value = "hellonitesh";

I am using this code:

var cookie = '@HttpContext.Current.Request.Cookies["doc1count"].Value';
alert(cookie);

but its giving me garbage value.

0

4 Answers 4

4

Try to separate client and server side Add cookies to responce on server:

HttpCookie myCookie= new HttpCookie("doc1count");
myCookie.Value = "hellonitesh";
HttpContext.Response.Cookies.Add(myCookie);

And retrieve it in javascript (You can find more examples here)

function getCookie(cname) {
    var name = cname + "=";
    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);
        if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
    }
    return "";
}
var myCookie = getCookie("doc1count")
Sign up to request clarification or add additional context in comments.

Comments

0

Try to use jquery.cookie plugin to manage cookie at client end. Apart from this, I can see in your C# code you are not posting the cookie variable. So you should do like following - HttpContext.Current.Response.Cookies.Add(new HttpCookie("cookie_name","cookie_value"));

Comments

0

You can probably just access it through ASP.NET variable by adding in the inline code I have right here. That's if you wanna be fairly simple about it, you can check if it contains anything with an if statement before assigning it I believe.

 var cookie = '<%= Request.Cookies["cookieID"].ToString() %>';
 alert(cookie);

Comments

0

Try this

var cookie = '@Request.Cookies["culture"].Value';

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.