Click here to Skip to main content
Click here to Skip to main content

Using Ajax, Beyond UpdatePanel

, 21 Sep 2008
Rate this:
Please Sign up or sign in to vote.
Using PageMethods

Introduction

This is an article about using Ajax beyond UpdatePanel.

Background

This article discusses using PageMethod in ASP.NET Ajax.

I have always been wondering about the UpdatePanel in Ajax, at times it just looks like a Magic Wand to me. If you already have an aspx and want to incorporate Ajax, just touch this Magic Wand and your page is Ajax ready! However, one more such Magic Wand provided in Microsoft Ajax is ScriptServices and PageMethods. These two are equally (if not more) handy when we want to Ajaxify our page, compared to UpdatePanel. In this article, I would take a look at these two as an alternative to UpdatePanel. I will try to demonstrate this with one example.

Before we begin working on the example, given below are captured notes from MSDN on PageMethod and ScriptService just to make things handy.

Script Services

Microsoft ASP.NET AJAX enables you to call ASP.NET Web services (*.asmx files) from the browser by using client script. This enhances the user experience for the Web application. The page can call server-based methods without a post back and without refreshing the whole page, because only data is transferred between the browser and the Web server. ASP.NET AJAX automatically creates JavaScript proxy classes for Web services. Proxy classes are derived from the Sys.Net.WebServiceProxy class. You can call a Web service method by calling the corresponding method of the JavaScript proxy class. For details, see Calling Web Services from Client Script. ASP.NET AJAX also provides built-in support for JavaScript calls to ASP.NET application services such as profiles and membership authentication. For details, see ASP.NET Application Services.

Page Method

You can add static page methods to an ASP.NET page and qualify them as Web methods. You can then call these methods from script as if they were part of a Web service, but without creating a separate *.asmx file. To create Web methods in a page, import the System.Web.Services namespace and add a WebMethodAttribute attribute to each static method that you want to expose. To be able to call static page methods as Web methods, you must set the EnablePageMethods attribute of the ScriptManager control to true.

http://asp.net/ajax/documentation/live/tutorials/ExposingWebServicesToAJAXTutorial.aspx

Now let's begin with our example; one simple example, where we would have otherwise used UpdatePanel Wink | ;) .

I have a search/search results page, in which I have searchPanel which includes three controls, one textbox for entering the search keyword, one button for performing the search and one grid to display the search result. Apart from the search results panel, the page might typically include left hand side navigation menu and top header bar and bottom footer bar and right hand side context panels. In a usual approach, to Ajaxify this page, we would be wrapping the searchPanel with an update panel so that, upon performing a search, the whole page is not posted back. I will demonstrate below how to achieve a similar user experience without making use of update panel.

In this approach, we would not be putting the grid statically in the 'searchPanel' to show the search result. Rather we would create a PageMethod in which, after retrieving the search result, we would dynamically create a grid, bind the same with search result data source, and then return grid's HTML from the method. On the search button click, we would invoke one client side method, which would in turn invoke the above PageMethod, and upon retrieving the output from the PageMethod, we would set the same to a div's innerHTML.

That's it! Take a look at the following code. Here in the sample, I have considered an array list as search result data source. I am using the search keyword to populate to the array list, which can be typically replaced by a database call.

The sample does not include other parts of the page like left hand side navigation menu or header bar, etc. as those would not need any alteration compared to the use of update panel.
Going further, I intend to talk about incorporating other useful features of update panel like update progress, etc. with the page method approach, comparing these two approaches and which to use when, and why one approach performs better than the other. So stay tuned!

The HTML portion of the following code is *not* well formed, closing tags for divs, panels etc. are lost during submission. I am keeping the following code just for reference purposes, and have attached a working version of the code file.

 <%@ Page Language="C#" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<script  runat="server">
    [System.Web.Services.WebMethod]
    public static string GetSearchResult(string searchKeyword)
    {
        ArrayList searchResultRows = new ArrayList();
        Random random = null;
        for (int resultCount = 0; resultCount < 10; resultCount++)
        {
            random = new Random(resultCount);
            searchResultRows.Add(string.Concat(searchKeyword, random.Next().ToString()));
        }
        GridView resultRepeater = new GridView();
        resultRepeater.DataSource = searchResultRows;
        resultRepeater.DataBind();
        StringBuilder stringBuilder = new StringBuilder();
        System.IO.StringWriter textWriter = new System.IO.StringWriter(stringBuilder);
        HtmlTextWriter htmlTextWriter = new HtmlTextWriter(textWriter);
        resultRepeater.RenderControl(htmlTextWriter);
        return stringBuilder.ToString();
    }
</script>
<script type="text/javascript">
function PerformSearchViaPageMethod()
{
    var searchKeyWord = document.getElementById('searchKeywordBox').value;
    PageMethods.GetSearchResult
	(searchKeyWord, OnPerformSearchViaPageMethodCallComplete);
    return false;
}
function OnPerformSearchViaPageMethodCallComplete(asyncResult)
{
    var searchResultsContainer = document.getElementById('searchResultsDiv');
    searchResultsContainer.innerHTML = asyncResult;
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1"  runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1"  runat="server">

            <asp:ScriptManager ID="ScriptManager1" 
		runat="server" EnablePageMethods="true">
            
            <asp:Panel ID="searchPanel" runat="server">
                <asp:TextBox ID="searchKeywordBox" runat="server">
                <asp:Button ID="performSearchViaPage" runat="server" 
			OnClientClick="return PerformSearchViaPageMethod();"
                    Text="PerformSearchViaPage" />             
    </form>
</body>
</html>

History

  • 22nd September, 2008: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

ATANU.PODDER

Unknown
No Biography provided

Comments and Discussions

 
QuestionI have corrected it,thanks for the original Post Pinmembermasoudxxx20024-Nov-12 17:35 
aspx file:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="! Pagemethod with scriptmanager no ajax.aspx.cs" Inherits="Pagemethod" %>
 
<!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 id="Head1"  runat="server">
    <title>Untitled Page</title>
    <script type="text/javascript">
function PerformSearchViaPageMethod()
{
    var searchKeyWord = document.getElementById('searchKeywordBox').value;
    PageMethods.GetSearchResult
    (searchKeyWord, OnPerformSearchViaPageMethodCallComplete);
    return false;
}
function OnPerformSearchViaPageMethodCallComplete(asyncResult)
{
    var searchResultsContainer = document.getElementById('searchResultsDiv');
    searchResultsContainer.innerHTML = asyncResult;
}
</script>
</head>
<body>
    <form id="form1"  runat="server">
 
            <asp:ScriptManager ID="ScriptManager1"
        runat="server" EnablePageMethods="true"></asp:ScriptManager>
 
            <asp:Panel ID="searchPanel" runat="server">
                <asp:TextBox ID="searchKeywordBox" runat="server"></asp:TextBox>
                <asp:Button ID="performSearchViaPage" runat="server"
            OnClientClick="return PerformSearchViaPageMethod();"
                    Text="PerformSearchViaPage" />
                    </asp:Panel>
                    <div id="searchResultsDiv"></div>
    </form>
</body>
</html>
 

 
------------
CS code behind file
using System;
using System.Collections;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
public partial class Pagemethod : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
 
}
 
[System.Web.Services.WebMethod]
public static string GetSearchResult(string searchKeyword)
{
ArrayList searchResultRows = new ArrayList();
Random random = null;
for (int resultCount = 0; resultCount < 10; resultCount++)
{
random = new Random(resultCount);
searchResultRows.Add(string.Concat(searchKeyword, random.Next().ToString()));
}
GridView resultRepeater = new GridView();
resultRepeater.DataSource = searchResultRows;
resultRepeater.DataBind();
StringBuilder stringBuilder = new StringBuilder();
System.IO.StringWriter textWriter = new System.IO.StringWriter(stringBuilder);
HtmlTextWriter htmlTextWriter = new HtmlTextWriter(textWriter);
resultRepeater.RenderControl(htmlTextWriter);
return stringBuilder.ToString();
}
}
masoudxxx

GeneralJust What I Needed. . . Pinmemberzdlewis20-Sep-11 5:29 
GeneralIncorrect Pinmemberinetfly12322-Sep-08 3:22 
GeneralRe: Incorrect PinmemberATANU.PODDER22-Sep-08 6:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140814.1 | Last Updated 22 Sep 2008
Article Copyright 2008 by ATANU.PODDER
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid