User Id :    Password :      New Member   Forgot Password  
 
Call CSharp Method by JavaScript in ASP.NET
Description This article will explain how to call c# method using a JavaScript method in asp.net.   No. of Views     3991
  Rating     0
Author Sumit Gupta   Posted On     04 Jul 2010
Tags    

Sample Code   Download Code

Introduction

In this article i am explaining how to call a c# method using a JavaScript method. In the following example i simply input your name and concatenate Hello using c# method and that c# method is called using javascript method.

Code
1. First we create a page with one text box and one button as follow:



    Client Callback

    


    
    
Enter Your Name:


In above code on button click we call javascript GetMessage Method that in turn call UseCallback method.

2. Server side code
For this we have to implement IcallbackEventHandler interface. The interface requires to implement the RaiseCallbackEvent and the GetCallbackResult menthods, both of which work with the client script request. RaiseCallvackEvent enables us to do the work of retrieving the value from the page and do the operation whaterver we want and GetCallbackResult returns the result. In Page_Load event we include the creation and placement of the client callback script manager i.e. Page.ClientScript.GetCallbackEventReference this function will manage the requests and response and put to the web page using the Page.ClientScript.RegisterClientScriptBlock.


public partial class _Default : System.Web.UI.Page, ICallbackEventHandler
{
    private string _callbackResult = null;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.Request.Browser.SupportsXmlHttp)
        {
            string cbReference = Page.ClientScript.GetCallbackEventReference(this, "arg", "GetMessageFromServer", "context");
            string cbScript = "function UseCallback(arg, context)" +
                                "{" + cbReference + ";" + "}";
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "UseCallback", cbScript, true);
        }
    }

    #region ICallbackEventHandler Members
    
    public void RaiseCallbackEvent(string eventArg)
    {

        _callbackResult = "Hello " + eventArg;
    }

    public string GetCallbackResult()
    {
        return _callbackResult;
    }

    #endregion

}



About Author

About Author I am Sumit Gupta working in 3 Pillar Global Pvt. Ltd as Module Lead. I have 7+ year of experience in .Net technologies. I love to explore new technologies and write technical article. Sumit Gupta
No Photo
 
Country India
Company 3 Pillar Global Pvt. Ltd.
Home Page http://www.facebook.com/sumitgupta1225

Rate this article

Rating options from poor, fair, good, very good to excelent.  
 

Comments

   
Write your comment here.
Comment
Verification Code