Friday, September 19, 2014

Create an Ajax Web Client for OData Web API RESTful Service - HTTP-DELETE JSON


In this article we'll design a web client for deleting a record by sending an HTTP DELETE call via Ajax to an Web API OData RESTful service implemented using an ODataController. The design will be made applying Twitter Bootstrap.

This post uses an OData Web API  designed in a previous Web API ODataController tutorial. The  Twitter Bootstrap's setup can be learned in this post. Also, the OData protocol for the MVC Web API with ODataControllers can be seen at the Microsoft Asp.Net site

We want to send an Ajax HTTP  DELETE request to the OData HTTP Web API service to delete an item, using this screen :
Ajax Web Client for OData Web API RESTful Service - HTTP-DELETE JSON



First create the MVC application as an empty web site:




Import the style and the script files  (you can learn the Twitter Bootstrap installing instructions here)


Take a look at the Web API ODataController class, to see the Delete( int  ) method that we're using:



The Delete() action method requires an integer ID , returning an  IHttpActionResult object.

Ajax Web Client for OData Web API RESTful Service - HTTP-DELETE JSON



Create a new web client for the OData service:


Add the references to the Twitter Bootstrap:



Then we add a DOM element for selecting the KEY  of the record to delete:

Next, we create all the input tags for showing the record's details:


This is the markup to copy-paste:

   <div class="panel panel-default">            <div class="panel-heading row">                <div class="text-muted col-xs-6">                    <h2>Message Details</h2>                </div>                <div class="text-muted col-xs-3">                    <div class="editor-label">                        ID                    </div>                    <div class="editor-field">                        <input type="number" name="ID" value="3" class="form-control" />                    </div>                </div>
            </div>            <div class="panel-body text-muted">                <div class="row">                    <div class="col-xs-6">                        <div class="editor-label">                            To                        </div>                        <div class="editor-field">                            <input type="text" name="To" class="form-control" />                        </div>                    </div>                    <div class="col-xs-6">                        <div class="editor-label">                            From                        </div>                        <div class="editor-field">                            <input type="text" name="From" class="form-control" />
                        </div>                    </div>                    <div class="col-xs-12">                        <div class="editor-label">                            Heading                        </div>                        <div class="editor-field">                            <input type="text" name="Heading" class="form-control" />
                        </div>                    </div>                    <div class="col-xs-12">                        <div class="editor-label">                            Body
                        </div>                        <div class="editor-field">                            <input type="text" name="Body" class="form-control" />
                        </div>                    </div>                    <div class="center">                        <div class="center">                            <br />                            <div class="row">                                <div class="col-lg-6">                                    <input class="btn btn-sm btn-default" value="See Message Details" />                                </div>                                <div class="col-lg-6">                                    <input class="btn btn-sm btn-default" value="Delete Message" />                                </div>                            </div>                        </div>                        <br />                        <div class="alert alert-success message"></div>                        <div class="alert alert-danger error"></div>                    </div>                </div>            </div>        </div>    </div>  





After the HTML, write the script, opening with the references to the jQuery and the Bootstrap  files:

When the "Details" button is clicked, the web page send an Ajax call containing the key of the item (inside the URI )   :



If the response was an 200 - OK, we show the item; in case of error, we display a message:


This is the code for the script:

  <script src="Scripts/jquery-2.1.1.js"></script>    <script src="Scripts/bootstrap.js"></script>    <script>        $(function () {            $("div.message").css("display", "none");            $("div.error").css("display", "none");
            $("input.btn[value*=Details]").click(function () {
                var id = $("input[name=ID]").val();                $.ajax({                    url: "http://localhost:6954/OData/Notes(" + id + ")",                    type: "GET",                    data: id,                    dataType: "json",                    contentType: "application/json",                    beforeSend: function (data) {                        //alert(id);                    },                    success: function (data) {                        var note = data;                        $("div.error").css("display", "none");                        $("div.message").css("display", "block");                        $("div.message").text("The Message with ID = " + id + " was retrieved successfully!!!");                        $("input[name=To]").val(note.To);                        $("input[name=From]").val(note.From);                        $("input[name=Heading]").val(note.Heading);                        $("input[name=Body]").val(note.Body);                    },                    error: function (msg) {                        var oError = JSON.parse(msg.responseText);                        fnError("Error : " + oError.error.innererror.message, id);                    }                })            });
            function fnError(msg, id) {                $("div.message").css("display", "none");                $("div.error").html("The message with ID = " + id + " does not exist. Try again.");                $("div.error").css("display", "block");            }



The method inside the ODataController renders the required item:



Now, we need an $.ajax() method to DELETE the selected record, using the HTTP DELETE verb:



This is the code for copy-paste in your project:

    $("input.btn[value*=Delete]").on("click", function () {
                var id = $("input.form-control[name*=ID]").val();
                 
                $.ajax({
                    url: "http://localhost:6954/OData/Notes(" + id + ")",
                    type: "DELETE",
                    data: id,
                    contentType: "application/json",
                    dataType: "json",
                    success: function (data) {
                        $("div.error").html(data.responseText); 
                    },
                    error: function (msg) {                                                
                         
                        if (msg.status == "410") {
                            $("div.message").text('The item was successfuly deleted.');
                        }
                    }
                });
            });
        })
    </script>


Here, we send an Ajax HTTP DELETE request to the OData Web API web service. Notice that the response for an OK has been defined as code 410 ("Gone"), that means that the Ajax request receives an ERROR by response, so we handle it in the error callback of the $.ajax() method!!!!!!

Run the application: the User retrieves the item's details, and clicks the second button, deleting the record:





The Ajax request reaches the OData Web API service, which we built in a previous article about   OData v4.0 WebAPI  updating  (HTTP PUT & HTTP PATCH) that can be found here.
This is the Delete() method which handles the HTTP DELETE request at the OData service:



As you see, we just delete the item, sending an "Gone" status message. Remember that "Gone" is the error 410, therefore we handle it at client side at the error callback.

That's all!!!!

In this article we've seen step by step how to create a web client which deletes a record by sending an HTTP DELETE Ajax request to an WebAPI OData RESTful service implemented with an MVC ODataController.
Enjoy OData Web API  !!!!

By Carmel Shvartzman

עריכה: כרמל שוורצמן