ClientScriptManager, .Net 2.0 class which I found really cool and useful to make a callback without posting back the Web Page. Follow with the below example for understanding it.
Note: Replace [ by "<" and ] by ">"
Example:
1. Create a Web application application project and copy the below code to aspx page
[%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ClientScriptManagerExample._Default" %]
[html]
[head runat="server"]
[title]ClientScriptManager Example[/title]
[script type="text/javascript" language="javascript"]
function ReceiveServerData(result, context)
{
alert(result);
}
[/script]
[/head]
[body]
[form id="form1" runat="server"]
[asp:TextBox ID="txtInput" runat="server"][/asp:TextBox]
[asp:Button ID="btnClick" Text="Click" runat="server" OnClientClick="NoPostback(); return false;" /]
[div]
[/div]
[/form]
[/body]
[/html]
[script]
function NoPostback()
{
CallServer(document.getElementById('txtInput').value);
}
[/script]
2. Code Behind. Copy the following code
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.UI;
namespace ClientScriptManagerExample
{
public partial class _Default : System.Web.UI.Page, ICallbackEventHandler
{
string strResult = "";
protected void Page_Load(object sender, EventArgs e)
{
ClientScriptManager csm = Page.ClientScript;
string strCallbackReference = csm.GetCallbackEventReference(this, "arg", "ReceiveServerData", "");
string strCallServer = "function CallServer(arg){" + strCallbackReference + " };";
csm.RegisterClientScriptBlock(this.GetType(), "CallServer", strCallServer, true);
}
public void RaiseCallbackEvent(string strInput)
{
strResult = "You typed: " + strInput;
}
public string GetCallbackResult()
{
return strResult;
}
}
}
3. Execute the application to see that it calls serverside function without having a postback
This is a simple program to demonstrate. One can extend this to use for anything.
No comments:
Post a Comment