Calling a .NET DLL Code on HTML File Using Microsoft .NET Handler and JSON

The objective of this article is to explain how to use an .ashx handler to access a DLL or any server on an HTML page using JSON to make the server side/DB call very fast in a simple manner.

This can be done using the following files in a project:

  • HTML: The UI of the project
  • JS: A JavaScript file to call the handler asynchronously
  • .ASHX Hander: to call the API
  • .DLL: .NET API Code to access DB or any business logic

Kindly, use the following to do that.

  1. Create a DLL
  2. Consume the DLL in Web project

Create the DLL

  1. Create a ClassLibrary project (ClassLibrary1) and add a class file into it named (Class1.cs)
  2. Add the following sample method into it and build the DLL:
    public int AddNumber(int num1, int num2)
    {
        return num1 + num2;
    }

Consume the DLL in Web

  1. Create a new .Net Web project and add a default.htm file and make it as the start-up file.
  2. Add the reference of SampleLibrary project created above.
  3. Add a .JS file (sample.js) and .ashx (sample.ashx) file into the project.
  4. Add a Generic Handler (Handler.ashx) file into the project and write the following code to access the DLL code.
  5. Add a reference for System.Web.Extensions.dll

    public void ProcessRequest(HttpContext context)

    {

        context.Response.ContentEncoding = System.Text.Encoding.UTF8;

        context.Response.ContentType = "text/html";

        var strResult = string.Empty;

        switch (context.Request.QueryString["RequestType"].Trim())

        {

            case "AddNum":

                strResult = this.AddNumber(

                        Convert.ToInt32(context.Request["number1"]),

                        Convert.ToInt32(context.Request["number2"]));

                break;

            }

            context.Response.Write(strResult);

        }

        public bool IsReusable

        {

            get

            {

                return false;

            }

        }

        public string AddNumber(int number1, int number2)

        {

            int total = 0;

            ClassLibrary1.Class1 sampleLib = new ClassLibrary1.Class1();

            total = sampleLib.AddNumber(number1, number2);

            var jsonData = new

              {

                  Total = total

              };
          JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();

            return javaScriptSerializer.Serialize(jsonData);

        }

Add the following lines in the default.htm file:

<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.1.min.js" type="text/javascript"></script>

 <script language="javascript" type="text/javascript" src="Sample.js"></script>

<body>

    <p>

        <input id="txtNumber1" type="text" /></p>

    <p>

        <input id="txtNumber2" type="text" /></p>

    <p>

        <input id="showSum" type="button" value="button" /></p>

</body>

Open the .JS file (sample.js) added previously and write the following code to access the handler:

$(document).ready(function() {

    $('body').delegate("#showSum", 'click', function() {
       var number1 = $("#txtNumber1").val();
        var number2 = $("#txtNumber2").val();
        CallHandlerSync("Handler.ashx?RequestType=AddNum", { 'number1': number1, 'number2': number2 });
    });
});

function CallHandlerSync(inputUrl, inputdata) {
    $.ajax({
        url: inputUrl,
        contentType: "application/json; charset=utf-8",
        data: inputdata,
        async: false,
        success: function(result) {
            var objResult = $.parseJSON(result);
            alert(objResult.Total);
        },
        error: function() {
            alert("Error...");
        }
    });
}