Home How to get Cookie set with Response.SetCookie(cookie) from Asp MVC using javascript
Reply: 1

How to get Cookie set with Response.SetCookie(cookie) from Asp MVC using javascript

Ibanez1700
1#
Ibanez1700 Published in 2017-09-14 08:07:20Z

I have set my cookie in the login section like so:

var cookie = new HttpCookie("sys_user_id", (query.UserAccountId).ToString())
{
    Expires = DateTime.Now.AddDays(1)
};
Response.SetCookie(cookie);

I can access and change to integer the same cookie at the view using this code:

<script>
    var sysUserId = @Convert.ToInt32(HttpContext.Current.Request.Cookies["sys_user_id"].Value);
</script>

but if I put this in a .js file, I get error at @Convert.ToInt32(HttpContext.Current.Request.Cookies["sys_user_id"].Value);. It is because the .js file cannot read the razor syntax. Is there a way to get my "sys_user_id" cookie and convert it to an integer using javascript so I can place it in my .js file?

Ibanez1700
2#
Ibanez1700 Reply to 2017-09-14 08:18:43Z

For those who have not yet got the answer to this kind of question, this is how I did it.

I created a new function like so:

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

then I called my "sys_user_id" cookie using this code:

var sysUserId = getCookie("sys_user_id);

This is the post for this answer: How to get server side cookies value in javascript?

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.441359 second(s) , Gzip On .

© 2016 Powered by cudou.com design MATCHINFO