In the ASP.NET any server side event fired means the entire
page will refresh or resend to server and return back. In the form if you
submit the one simple button event the full page will get refresh. Then how to avoid this or how to make my page
to update data without refresh ?. For
that we have one option called IcallbackEventHandler
Interface. Using this we can achieve without post back or refresh the page.
First we need in add IcallbackEventHandler interface in our aspx.cs page. The below code
I have added IcallbackEventHandler in my main partial
class.
public partial class Default : System.Web.UI.Page,
System.Web.UI.IcallbackEventHandler
{
protected void Page_Load(object sender, EventArgs e)
{
If (!IsPostBack)
{
}
//Register the call server function in C# code.
ClientScriptManager cm = Page.ClientScript;
String cbReference = cm.GetCallbackEventReference(this, "arg","ReceiveServerData", "");
String callbackScript = "function CallServer(arg, context) {" +cbReference + "; }";
cm.RegisterClientScriptBlock(this.GetType(),"CallServer", callbackScript, true);
}
//Java script will call this event
public void RaiseCallbackEvent(String
eventArgument)
{
}
//return the string to javascript function
public string GetCallbackResult()
{
string
result = "JSON OBJECT";
return
result;
}
}
In the Default.aspx page you need to add latest Jquery
script first. In the java script function we need to create below function for
call the server side function in the Java script.
<script src="Scripts/jquery.min.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
function CallServerData() {
//Call the server side function
CallServer("", "");
}
//Returning from the server side function.
function ReceiveServerData (arg, context) {
var splitarg = arg.toString().split("~");
var obj = eval(splitarg[0]);
updateReports(obj, '#Reports');
}
//Your custom code to update in the table.
function updateReports(data, id) {
var obj = $(id + ' > tbody');
obj.empty();
var mystyle = "style='font-weight:bold'; font-size:11px;color:#000;";
for (var j = 0; j < data.length - 1; j++) {
obj.append("+ data[j + 1][keys[i]] + " "
}
}
}
</script>
In the HTML code to call the server side event like below
<asp:Button ID="btnGetData"
runat="server"
Text="Save"
OnClientClick="return
CallServerData();" />
The server side function returns the JSON string. So we need to fill that information to the HTML Table. The UpdateReports Javascript function will load JSON string to simple HTML Table.
<table width="900px" cellpadding="5" cellspacing="0" align="center" id="Reports">
<thead>
<tr>
<th>
ID
</th>
<th>
Name
</th>
<th>
Class
</th>
<th>
</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
The above code will help you to get know Call server side
function in the java script easily.
No comments:
Post a Comment