Get (Retrieve) Cookies value in jQuery which set from Code Behind in ASP.Net

Last Reply 19 days ago By arunkurmi

Posted 19 days ago

 How to get cookies value in jquery which is define in c# code

HttpCookie cookie = new HttpCookie("UserInfo");
cookie["username"] = username;
cookie["userid"] = userid;
HttpContext.Current.Response.Cookies.Add(cookie);

on Default.aspx

i define this cookies in my page behind c# in handler 

but now i want get this cookies

$(function () {
    var a = document.cookie["username"];
    alert(a);
});

it not work

Posted 19 days ago Modified on 19 days ago

Hi SajidHussa,

Check this sample. now please take its reference.

HTML

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/jquery.cookie/1.3.1/jquery.cookie.js"></script>
<script type="text/javascript">
    $(function () {
        $("[id*=btnSubmit]").on("click", function () {
            var userInfo = $.cookie("UserInfo");
            alert(userInfo.split("&")[0] + "\n" + userInfo.split("&")[1]);
            return false;
        });
    });
</script>
<form id="form1" runat="server">
<div>
    <asp:Button ID="btnSubmit" Text="Submit" runat="server" />
</div>
</form>

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    string userName = "AspSnippets";
    string userId = "1";
    HttpCookie cookie = new HttpCookie("UserInfo");
    cookie["UserName"] = userName;
    cookie["UserID"] = userId;
    HttpContext.Current.Response.Cookies.Add(cookie);
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    Dim userName As String = "AspSnippets"
    Dim userId As String = "1"
    Dim cookie As HttpCookie = New HttpCookie("UserInfo")
    cookie("UserName") = userName
    cookie("UserID") = userId
    HttpContext.Current.Response.Cookies.Add(cookie)
End Sub

Screenshot