Hi asp777,
Refer below sample.
HTML
<script src="scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
function Write() {
$.ajax({
type: "POST",
url: "Default.aspx/Write",
data: '{name: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json"
});
}
</script>
<div>
Your Name :
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
<input id="btnGetTime" type="button" value="Write" onclick="Write()" />
<asp:Button Text="Read" runat="server" OnClick="Read" />
<asp:Button Text="Refresh" runat="server" OnClick="Refresh" />
</div>
Namespaces
C#
using System.Web.Services;
VB.Net
Imports System.Web.Services
Code
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
if (Request.Cookies["Name"] != null)
{
HttpCookie nameCookie = Request.Cookies["Name"];
nameCookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(nameCookie);
}
}
}
protected void Refresh(object sender, EventArgs e)
{
Response.Redirect(Request.Url.AbsoluteUri);
}
[WebMethod]
public static void Write(string name)
{
HttpCookie nameCookie = new HttpCookie("Name");
nameCookie.Values["Name"] = name;
HttpContext.Current.Response.Cookies.Add(nameCookie);
}
protected void Read(object sender, EventArgs e)
{
HttpCookie nameCookie = HttpContext.Current.Request.Cookies["Name"];
string name = nameCookie != null ? nameCookie.Value.Split('=')[1] : "";
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('" + name + "');", true);
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
If Request.Cookies("Name") IsNot Nothing Then
Dim nameCookie As HttpCookie = Request.Cookies("Name")
nameCookie.Expires = DateTime.Now.AddDays(-1)
Response.Cookies.Add(nameCookie)
End If
End If
End Sub
Protected Sub Refresh(ByVal sender As Object, ByVal e As EventArgs)
Response.Redirect(Request.Url.AbsoluteUri)
End Sub
<WebMethod()>
Public Shared Sub Write(ByVal name As String)
Dim nameCookie As HttpCookie = New HttpCookie("Name")
nameCookie.Values("Name") = name
HttpContext.Current.Response.Cookies.Add(nameCookie)
End Sub
Protected Sub Read(ByVal sender As Object, ByVal e As EventArgs)
Dim nameCookie As HttpCookie = HttpContext.Current.Request.Cookies("Name")
Dim name As String = If(nameCookie IsNot Nothing, nameCookie.Value.Split("="c)(1), "")
ClientScript.RegisterStartupScript(Me.GetType(), "alert", "alert('" & name & "');", True)
End Sub
Screenshot