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; }
        }
    }

}

1 comment:

parthinesabine said...

MGM National Harbor Casino Resort - JTHub
MGM National Harbor is one 목포 출장안마 of the 경상북도 출장마사지 biggest casinos in the United 목포 출장안마 States and the largest resort in the world. From its grandstand, Feb 통영 출장마사지 11, 2022 삼척 출장마사지 - Feb 13, 2022MGM National Harbor Casino Resort