Hello all,
Working with ASP.NET web forms, if we want to post or fetch the data from server asynchronously we use ICallbackEventHandler which is an interface that can be implemented in any class by inheriting it.
ICallbackEventHandler is an interface which comes with two methods:
- RaiseCallbackEvent((string eventArgument)
- GetCallbackResult() :
To impliment this we have the following code packet :
In JavaScript:
function saveUserData() {
var name = $("#txtUserName").val();
var id= $("#txtUserId").val();
if(name != "" && id != ""){
var data = "SaveData"+"_"+name + "_" + id;
CallBackEndServer(data, "SaveData");
}
}
function ReceiveServerData(rValue, Context) {
if (rValue != null && rValue != "") {
var serverData = JSON.parse(rValue);
if (serverData .length != 0) {
if (Context.toUpperCase() == 'SAVEDATA') {
// call your function here to show fetched data on UI
}
}
}
}
In ASPX:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
Your Name :
</td>
<td>
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Your Id:
</td>
<td>
<asp:TextBox ID="txtUserId" runat="server"></asp:TextBox>
</td>
</tr>
<input id="btnUserDetails" type="button" value="Show User Details" onclick ="saveUserData()" />
</div>
</form>
</body>
</html>
In C# :
using System;
using System.Web;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.Net;
using System.Web.Services;
public partial class _Default : System.Web.UI.Page, ICallbackEventHandler
{
protected string Script;
private JavaScriptSerializer javaScriptSerializer;
protected void Page_Load(object sender, EventArgs e)
{
javaScriptSerializer = new JavaScriptSerializer();
string m_callbackScript = Page.ClientScript.GetCallbackEventReference(this, "arg", "ReceiveServerData", "context");
string m_callbackScript = "function CallBackEndServer(arg, context)" + "{ " + m_cbReference + "} ;";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "CallCustomFieldServer", m_callbackScript, true);
}
string callbackRetStr = "";
public string GetCallbackResult()
{
return callbackRetStr;
}
public void RaiseCallbackEvent(string eventArgument)
{
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
object serverData = null;
string[] dataArr = eventArgument.Split("_", StringSplitOptions.None); ;
switch (dataArr[0])
{
case "SaveData":
serverData = // Your data acess code goes here
callbackRetStr = javaScriptSerializer.Serialize(serverData);
break;
}
}
}
0 Comment(s)