Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Javascript Ajax for ASP.NET

Tags:

javascript

c#

I've written some basic Javascript functions and would like to learn how to enable asynchronous postbacks within a C# 4.0/ASP.net project using this JS code.

For example, I have a script that increments a number when clicked. When clicked again, the number is decremented. I basically load the number from a database, then hide one <span> and show another with the corresponding decremented number on click. This is not complicated javascript; its a simple example. Now when I click the button I want to send this increment/decrement call back to the server to update the database's number.

I realize that I can accomplish something akin to this example using the AJAX Control Toolkit's toggle button. I, however, want to know how to use my OWN javascript to create AJAX functionality.

How do I accomplish this using C# and my custom Javascript code?

I'm not opposed to using the ASP.net AJAX library, I just don't want to use a ready built control. I want to learn the process of creating my own AJAX functionality. I would presume that I will have to use an asp:UpdatePanel, but I don't know how to call C# functions from the client side.

My javascript is not jQuery, in fact I want nothing to do with jQuery until I learn more about javascript and this process.

like image 982
Morgan Avatar asked Aug 24 '10 16:08

Morgan


1 Answers

Simple with no UpdatePanel:

First, add a Generic Handler to your project (.ashx). This will act as our Http endpoint. Our javascript will call it. We could (and probably should), use a web service endpoint but that requires processing the response and complicates the example. A handler returns plain text.

<%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.Web;

public class Handler : IHttpHandler
{
    // We'll use a static var as our "database".
    // Feel free to add real database calls to the increment
    // and decrement actions below.
    static int TheNumber = 0;

    public void ProcessRequest(HttpContext context)
    {       
        string action = context.Request.QueryString["action"];
        if (!string.IsNullOrEmpty(action))
        {
            if (action == "increment")
                TheNumber++;   //database update and fetch goes here
            else if (action == "decrement")
                TheNumber--;   //database update and fetch goes here           
        }
        context.Response.ContentType = "text/plain";
        context.Response.Write(TheNumber);
    }

    public bool IsReusable { get { return false; } }
}

Next, create your web page and add the async javascript.

<%@ Page Language="C#"%>
<html>
<head runat="server">    
    <script type="text/javascript">
    // An XMLHttpRequest object is required to make HTTP requests.
    // Try a couple instantiation strategies to handle different
    // browser implementations.
    function createXMLHttpRequest() {
        try { return new XMLHttpRequest(); } catch (e) { }
        try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { }
        try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { }
        alert("XMLHttpRequest not supported");
        return null;
    }

    function callHandler(action) {
        var xmlHttpReq = createXMLHttpRequest();
        // We're interested in an asychronous request so we define a 
        // callback function to be called when the request is complete.
        xmlHttpReq.onreadystatechange = function () {
            if (xmlHttpReq.readyState == 4 && xmlHttpReq.status == 200)
                document.getElementById("<%= lbl.ClientID%>").innerHTML 
                    = xmlHttpReq.responseText;
        }
        xmlHttpReq.open("GET", "Handler.ashx?action=" + action, true);
        xmlHttpReq.send(null);
    }  
    </script>
</head>
<body>
    <form id="Form1" runat="server">
    <div>
    The Number:&nbsp;<Label runat="server" id="lbl">0</Label>
    </div>
    <div>
        <asp:Button ID="Button1" runat="server" Text="Increment" 
            OnClientClick="callHandler('increment');return false;" />
        &nbsp;
        <asp:Button ID="Button2" runat="server" Text="Decrement" 
            OnClientClick="callHandler('decrement');return false;" />
    </div>
    </form>
</body>
</html>

The final flow is:

  • A web page user clicks the Increment or Decrement button which calls our javascript
  • Our javascript sends a request with the desired action in the querystring to Handler.ashx
  • Handler.ashx reads the querystring, increments or decrements its static variable, and returns the value
  • Our callback receives the value and updates our UI.
like image 113
Corbin March Avatar answered Sep 28 '22 23:09

Corbin March