This
article will show you how you can create a cookie using c#.net and how you can retrieve
the created cookie value using javascript in your asp.net application. So
creating cookie at server side code and retrieving cookie from client side
code.
So for this article first we will create a new asp.net application and add a page in this page add the below code.
So for this article first we will create a new asp.net application and add a page in this page add the below code.
using System;
using
System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using
System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class Cookies : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Cookies["Name"] == null)
{
string cookeValue = "aspdotnet-pools.com";
HttpCookie
userName = new HttpCookie("Name", cookeValue);
//
enable client-side access
userName.HttpOnly
= false;
Response.Cookies.Add(userName);
}
}
}
}
|
In above code first I have checked that weather the cookie exists or not if it not exists on that case I have created the cookies. Now check the highlighted part of the code. This code is provide permission weather the cookie is allowed to access at client end or using client side code like jquery and javascript.
Now we will
check the javascript code to retrieve the created cookie value using javascript.
function
GetCookieValue(cookieName) {
var value =
document.cookie.match('(^|;)\\s*' + cookieName + '\\s*=\\s*([^;]+)');
return value ?
value.pop() : '';
}
function
RetruveCookieValue() {
var cookeVal = GetCookieValue("Name");
alert(cookeVal);
}
|
In above code I have created a function which will return the cookie value and other will be called at the button click to chow the output. Now check the complete code.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Cookies.aspx.cs" Inherits="WebApplication1.Cookies" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>How to Read Cookie
Value Using JavaScript Ceated Using C#.Net In Asp.Net</title>
<script>
function
GetCookieValue(cookieName) {
var value =
document.cookie.match('(^|;)\\s*' + cookieName + '\\s*=\\s*([^;]+)');
return value ?
value.pop() : '';
}
function
RetruveCookieValue() {
var cookeVal = GetCookieValue("Name");
alert(cookeVal);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="button" value="Retrive Cooke Value" onclick="javascript:
RetruveCookieValue();" />
</div>
</form>
</body>
</html>
|
Now we have
done run the application to check the output.
0 comments:
Please let me know your view