pavanarya

Let us share the knowledge

Calling Methods Present In The Code-behind File Using ScriptManager

with one comment

In my previous post we saw how to call a web service from the java script .

So is it necessary to have a web service for just calling a single web method present in it. It requires over head in hosting this particular web service. So it would be nice if we can have that web method in our code behind file itself.
So in this post we will see the process involved in calling the methods present in the code behind file from java script code.

What is Page Methods

Page Methods is ajax allows us to call the methods present in the code behind file.

1.Create an empty web site application in the visual studio.

2.Add an aspx page to the project created above.

3. Add a method in the aspx.cs file(code behind file).

4.So in order to make this method available for calling from javascript we should declare it as web method.

5.So in order to make a method as web method we should include “using System.Web.Services;” namespace.

6.The methods we are going to call from the java script should be declared as static and it is a must.

So in my case i am adding a method TestWebService with single parameter.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        
        ScriptManager.RegisterClientScriptBlock(this,typeof(Page),"myscript","<script language='javascript'>alert('hai');</script>",false);

    }
   [WebMethod]
    public static string TestCodeBehind(string name)
    {
        return "Hai " + name;
    }
}

Now let us make a move the aspx page.

1.So in order to call the web method declared in the code behind file we should include the control to the aspx page.

2. Now add the property EnablePageMethods and make it as true. This is the property that will inject the javascript proxy(Microsft ajax javascript proxy) into the browser which will actually take care of the call internally.

<asp:ScriptManager ID="scriptmanager1" runat=server EnablePageMethods="true">
    </asp:ScriptManager>

3.By adding the above tag we got rights to call the method present in the code behind file. Now add the java script code to the aspx page that involves the call to the code behind file.

<script language=javascript>
            function callCodeBehindMethod() {
                PageMethods.TestCodeBehind("Pavan", onSuccess, onFailure);
            }
            function onSuccess(result) {
                alert(result);
            }
            function onFailure(result) {
                alert("There is an error");
            }

    </script>

So in the above code we are having a method called “callCodeBehindMethod” in which we are calling the code behind method TestCodeBehind(). Actually this particular method in aspx.cs file accepts single parameter of type string. But in this method we are passing 3 parameters. one is string that the method actually accepts and the other 2 that is onSuccess and onFailure are call back functions that are executed either if the request is successful or failure. Also we can have an optional parameter “userContext” to this method.

The other major thing in this method “callCodeBehindMethod” is PageMethods. In order to call the method we should use this “PageMethods” attribute. If we are calling a web service instead of Pagemethods we are supposed to use Webservice class name. As we are calling the code behind file we should use PageMethods.

Code for entire aspx page.

<%@ 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 language=javascript>
            function callwebservice() {
                PageMethods.TestWebService("Pavan", onSuccess, onFailure);
            }
            function onSuccess(result) {
                alert(result);
            }
            function onFailure(result) {
                alert("There is an error");
            }

    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:ScriptManager ID="scriptmanager1" runat=server EnablePageMethods="true">
    </asp:ScriptManager>
    <input type="button" id="btn1" runat="server" value="Button" name="Button" onclick="callwebservice()"/>

    </div>
    </form>
</body>
</html>

So in the above code we are having a button and on button’s onclick event we are calling the javascript method and inside that javascript method we are calling the page method.

Drawbacks of PageMethods

1. The major drawback of page methods is we cannot access .net controls like textbox ,gridview and other control in the page method that is declared in the code behind file.

For example we are having an textbox in the aspx page and we can access this in the code behind file but not in the TestCodeBehind() method which is declared as web method and also as static.

The reason behind this is inorder to make a method as page method it is compulsory to declare it as webmethod and static. And it is a basic oops principle that we cannot access non static methods and properties inside a static method.












About these ads

Written by pavanarya

December 24, 2011 at 1:01 pm

Posted in Ajax, Asp.net

One Response

Subscribe to comments with RSS.

  1. [...] In my previous post we saw how to call a method present in the code behind file using scriptmanager in web forms. [...]


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 68 other followers

%d bloggers like this: