admin管理员组

文章数量:1327661

I've made a cookie using asp 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.

I've made a cookie using asp 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.

Share Improve this question edited Oct 16, 2015 at 12:54 vivekkupadhyay 2,8911 gold badge24 silver badges36 bronze badges asked Oct 16, 2015 at 12:15 Mango PeopleMango People 311 gold badge1 silver badge7 bronze badges 0
Add a ment  | 

4 Answers 4

Reset to default 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")

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"));

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

Try this

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

本文标签: cread cookie in javascriptmade by aspnet ccodeStack Overflow