Click here to Skip to main content
15,894,017 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
Hi,

I'm having difficulty finding a good explanation or tutorial on how to send an Ajax request from one ASP.Net control to update from the server to another control.

Is UpdatePanel is the only solution and does it really avoid a postback?

Any help with this is greatly appreciated.
Posted
Updated 15-Mar-11 5:38am
v2
Comments
Albin Abel 15-Mar-11 12:08pm    
Apart from UpdatePanel, you can use your custom javascript with XMLHttp. You can use Ajax control toolkit. These are the alternatives
Albin Abel 15-Mar-11 12:20pm    
Added to that even JQuery has Ajax methods

1 solution

In most of the case UpdatePanel is a good choice, it is easy to use and saves your lot of partial-page rendering script generation time.yet there are alternate ways.

1. You may implement the ICallbackEventHandler

C#
public partial class CallBack_DB_aspx :
    System.Web.UI.Page, System.Web.UI.ICallbackEventHandler

A client side event triggers a callback to server which will return the result as string. you have to write client side display logic then.


Aspx page

XML
<%@ Page Language="C#" AutoEventWireup="true"
  CodeFile="ClientCallback.aspx.cs" Inherits="ClientCallback" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML
  1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
  <title>Client Callback Example</title>
  <script type="text/ecmascript">
    function LookUpStock()
    {
        var lb = document.getElementById("ListBox1");
        var product = lb.options[lb.selectedIndex].text;
        CallServer(product, "");
    }

    function ReceiveServerData(rValue)
    {
        document.getElementById("ResultsSpan").innerHTML = rValue;

    }
  </script>
</head>
<body>
  <form id="form1" runat="server">
    <div>
      <asp:ListBox ID="ListBox1" Runat="server"></asp:ListBox>
      <br />
      <br />
      <button type="Button" onclick="LookUpStock()">Look Up Stock</button>
      <br />
      <br />
      Items in stock: <span id="ResultsSpan" runat="server"></span>
      <br />
    </div>
  </form>
</body>
</html>


Code-behind

C#
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class ClientCallback : System.Web.UI.Page,
     System.Web.UI.ICallbackEventHandler
{
    protected System.Collections.Specialized.ListDictionary catalog;
    protected String returnValue;
    protected void Page_Load(object sender, EventArgs e)
    {
        String cbReference =
            Page.ClientScript.GetCallbackEventReference(this,
            "arg", "ReceiveServerData", "context");
        String callbackScript;
        callbackScript = "function CallServer(arg, context)" +
            "{ " + cbReference + ";}";
        Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
            "CallServer", callbackScript, true);

        catalog = new System.Collections.Specialized.ListDictionary();
        catalog.Add("monitor", 12);
        catalog.Add("laptop", 10);
        catalog.Add("keyboard", 23);
        catalog.Add("mouse", 17);

        ListBox1.DataSource = catalog;
        ListBox1.DataTextField = "key";
        ListBox1.DataBind();

    }

    public void RaiseCallbackEvent(String eventArgument)
    {
        if (catalog[eventArgument] == null)
        {
            returnValue = "-1";
        }
        else
        {
            returnValue = catalog[eventArgument].ToString();
        }
    }
    public String GetCallbackResult()
    {
        return returnValue;
    }
}




2. Using web service method

The .NET Framework enables you to call ASP.NET Web services (.asmx) methods from the browser asynchronously by using client script. The page can call server-based methods without a postback and without refreshing the whole page, because only data is transferred between the browser and the server.

ASPX file
XML
<%@ Page Language="C#" %>

<!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">
        <style type="text/css">
            body {  font: 11pt Trebuchet MS;
                    font-color: #000000;
                    padding-top: 72px;
                    text-align: center }

            .text { font: 8pt Trebuchet MS }
        </style>

        <title>Simple Web Service</title>

            <script type="text/javascript">

            // This function calls the Web Service method.
            function GetServerTime()
            {
                Samples.AspNet.ServerTime.GetServerTime(OnSucceeded);
            }

            // This is the callback function that
            // processes the Web Service return value.
            function OnSucceeded(result)
            {
                var RsltElem = document.getElementById("Results");
                RsltElem.innerHTML = result;
            }

        </script>

    </head>

    <body>
        <form id="Form1" runat="server">
         <asp:ScriptManager runat="server" ID="scriptManager">
                <Services>
                    <asp:ServiceReference path="ServerTime.asmx" />
                </Services>
            </asp:ScriptManager>
            <div>
                <h2>Server Time</h2>
                    <p>Calling a service that returns the current server time.</p>

                    <input id="EchoButton" type="button"
                        value="GetTime" onclick="GetServerTime()" />
            </div>
        </form>

        <hr/>

        <div>
            <span id="Results"></span>
        </div>

    </body>

</html>



web service - Code-behind

C#
<%@ WebService Language="C#" Class="Samples.AspNet.ServerTime" %>

C#
using System;
using System.Web;
using System.Web.Services;
using System.Xml;
using System.Web.Services.Protocols;
using System.Web.Script.Services;

namespace Samples.AspNet
{

    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ScriptService]
    public class ServerTime : System.Web.Services.WebService
    {

        [WebMethod]
        public string GetServerTime()
        {
            return String.Format("The server time is {0}.",
                DateTime.Now);

        }

    }

}



3. Lower - Level Client Callback

The previous example shows how to call Web services from client script by calling the automatically generated proxy classes for the Web service. You can also make lower-level calls to Web services from client script. You might do this if you have to manage the communication layer or examine the data that is being sent to or from the server. To call Web services in this manner, you use the WebRequest class.

The following example shows how to use a WebRequest object to implement GET and POST Web requests that connect to the specified URLs (HTTP end points).

C#
// ConnectingEndPoints.js

var resultElement;

function pageLoad()
{
    resultElement = $get("ResultId");
}

// This function performs a GET Web request.
function GetWebRequest()
{
    alert("Performing Get Web request.");

    // Instantiate a WebRequest.
    var wRequest = new Sys.Net.WebRequest();

    // Set the request URL.
    wRequest.set_url("getTarget.htm");
    alert("Target Url: getTarget.htm");

    // Set the request verb.
    wRequest.set_httpVerb("GET");

    // Set the request callback function.
    wRequest.add_completed(OnWebRequestCompleted);

    // Clear the results area.
    resultElement.innerHTML = "";

    // Execute the request.
    wRequest.invoke();
}

// This function performs a POST Web request.
function PostWebRequest()
{
    alert("Performing Post Web request.");

    // Instantiate a WebRequest.
    var wRequest = new Sys.Net.WebRequest();

    // Set the request URL.
    wRequest.set_url("postTarget.aspx");
    alert("Target Url: postTarget.aspx");

    // Set the request verb.
    wRequest.set_httpVerb("POST");

    // Set the request handler.
    wRequest.add_completed(OnWebRequestCompleted);

    // Set the body for he POST.
    var requestBody =
        "Message=Hello! Do you hear me?";
    wRequest.set_body(requestBody);
    wRequest.get_headers()["Content-Length"] =
        requestBody.length;

    // Clear the results area.
   resultElement.innerHTML = "";

    // Execute the request.
    wRequest.invoke();
}


// This callback function processes the
// request return values. It is called asynchronously
// by the current executor.
function OnWebRequestCompleted(executor, eventArgs)
{
    if(executor.get_responseAvailable())
    {
        // Clear the previous results.

       resultElement.innerHTML = "";

        // Display Web request status.
       resultElement.innerHTML +=
          "Status: [" + executor.get_statusCode() + " " +
                    executor.get_statusText() + "]" + "<br/>";

        // Display Web request headers.
       resultElement.innerHTML +=
            "Headers: ";

       resultElement.innerHTML +=
            executor.getAllResponseHeaders() + "<br/>";

        // Display Web request body.
       resultElement.innerHTML +=
            "Body:";

      if(document.all)
        resultElement.innerText +=
           executor.get_responseData();
      else
        resultElement.textContent +=
           executor.get_responseData();
    }

}
if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();
 
Share this answer
 
Comments
Sandeep Mewara 15-Mar-11 15:03pm    
Decent enough effort in answering. No idea why was it downvoted. Countered and upvoted. 5!
_Ashish 16-Mar-11 3:40am    
Thx

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900