I have created and set the cookie through C# class and I want to use this cookie value in jquery file.
Like I have created and set cookie ...
HttpCookie myCookie = new HttpCookie("LoggedUserId");
myCookie.Value = newUser.UserId.ToString();
and this cookie value want to use in jquery file
var loggedUserId = $.cookie('LoggedUserId');
but it is returning undefined.
I also tried this..
var loggedUserId = '@HttpContext.Current.Request.Cookies["LoggedUserId"].Value';
But it is returning @HttpContext.Current.Request.Cookies["LoggedUserId"].Value
as a string
in loggedUserId
.
Please suggest me to move forward. Thanks
If you are putting your code on page then your code will run perfectly
<script type="text/javascript">
var cookie = '@HttpContext.Current.Request.Cookies["mycookie"].Value';
alert(cookie);
</script>
But in case, you are adding your code in js file then this code might do your work.
function getCookieValue(name) {
cookieList = document.cookie.split('; ');
cookies = {};
for (i = cookieList.length - 1; i >= 0; i--) {
cookie = cookieList[i].split('=');
cookies[cookie[0]] = cookie[1];
}
return cookies[name];
}
Please see this link for more detail. Hope it can help you.
http://dotnet-concept.com/Article/2014/12/34/Create-Update-and-Get-cookie-value-through-javascript
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.