Wednesday, September 14, 2016

How to POST JSON object to ASP.NET httphandler API using XmlHttpRequest and Javascript

This example show how to post a JSON object to asp.net http handler using xmlhttprequest in JavaScript.

Passing objects this way will help to maintain the same object model in UI , business object and database. Similar to MVC framework - but here you are building your own framework and have more control over the functionalities and performance.

JS
<script>

        function postData() {
            var xhr = new XMLHttpRequest();
            /*set the asp.net end point*/
            var url = "departmentAPI?action=add";
            /*set method as post*/
            xhr.open("POST", url, true);
            xhr.setRequestHeader("Content-type", "application/json");
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    var json = JSON.parse(xhr.responseText);
                    console.log(json)
                }
            }
            /*create object*/
            var department = {};
            department.department_name = "Finance";
            var data = JSON.stringify(department);
            /*post data to server*/
            xhr.send(data);

        }
        /*call the function*/
        postData();
    </script>


C#/.net

public class DepartmentAPI : IHttpHandler
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
      public void ProcessRequest(HttpContext context)
        {
            /*read data from server side*/
            string jsonString = String.Empty;
            context.Request.InputStream.Position = 0;
            using (StreamReader inputStream = new StreamReader(context.Request.InputStream))
            {
                jsonString = inputStream.ReadToEnd();
            }
            DepartmentBO department = serializer.Deserialize<DepartmentBO>(jsonString);
        }


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

}