Calling A .NET DLL Code On HTML File Using Microsoft .NET Handler And JSON

Introduction

The objective of this article is to explain how to use a .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.

  • Create a DLL.
  • Consume the DLL in the Web project.

How to Create the DLL in .NET?

public int AddNumber(int num1, int num2)
{
    return num1 + num2;
}
  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.

How to Consume the DLL on the Web?

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

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.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>
    <script src="Sample.js" type="text/javascript"></script>
</head>
<body>
    <p>
        <input id="txtNumber1" type="text" />
    </p>
    <p>
        <input id="txtNumber2" type="text" />
    </p>
    <p>
        <input id="showSum" type="button" value="Calculate Sum" />
    </p>
</body>
</html>

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...");
        }
    });
}


Similar Articles