Here i am going to give code snippets for ICallbackEventHandler through which we can make asynchronous calls to server so that we can avoid post back of the web page.
Firstly we have to implement the interface ICallbackEventHandler,public partial class _Default : System.Web.UI.Page, ICallbackEventHandler
then we have to implement two methods in the interface ICallbackEventHandler,
- GetCallbackResult
- RaiseCallbackEvent
#region ICallbackEventHandler MembersHere for simplicity i am returning a static data.You can return dynamic data also.Then you need to Get Call back Event Reference through Page.ClientScript
public string GetCallbackResult()
{
return result;
}
public void RaiseCallbackEvent(string eventArgument)
{
result = "Call Back Result";
}
#endregion
so now our class look like this,
string callback = ClientScript.GetCallbackEventReference(this, "arg", "GetName", "context");
string script = "function CallBack(arg,context){" + callback + ";}";
ClientScript.RegisterClientScriptBlock(this.GetType(), "CB", script, true);
Now add one textbox and one HTML Button to the designer.For call back we should use HTML Button.In the onclick event of HTML Button call the javascript method GetValue();
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class _Default : System.Web.UI.Page, ICallbackEventHandler
{
public string result;
protected void Page_Load(object sender, EventArgs e)
{
string callback = ClientScript.GetCallbackEventReference(this, "arg", "GetName", "context");
string script = "function CallBack(arg,context){" + callback + ";}";
ClientScript.RegisterClientScriptBlock(this.GetType(), "CB", script, true);
}
#region ICallbackEventHandler Members
public string GetCallbackResult()
{
return result;
}
public void RaiseCallbackEvent(string eventArgument)
{
result = "Call Back Result";
}
#endregion
}
Our Javascript code looks like,
Build and Run the application.Now while clicking HTML Button the textbox is populated with the value from the server without posting the page.
function GetValue()
{
CallBack();
}
function GetName(arg,context)
{
document.getElementById('txtPercentage').value=arg;
}
This is very useful in practical scenarios.
For more details, visit http://msdn.microsoft.com/en-us/library/system.web.ui.icallbackeventhandler.aspx
1 comments:
Nice Post.
Is it possible to implement the same code in sharepoint custom webpart 2010
protected override void OnLoad(EventArgs e)
in this case the page is full postback.
Post a Comment