Friday, September 5, 2014

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


In this post we'll create a web client for retrieving records' details from a database by sending an HTTP GET request via Ajax to an Web API OData RESTful service implemented with the ODataController. We'll build the details form by means of the Twitter Bootstrap.
We'll perform an Ajax GET request using the OData protocol in order to get the values of an Entity in JSON format.

In this application we're using an OData Web API which we created in a previous Web API ODataController tutorial. The details for installing the Bootstrap can be found  in this very short article.
The OData protocol's conventions for MVC Web API with ODataControllers can be found in the Microsoft Asp.Net official site

For this article we are using an Entity named "Note" , and we want to send a GET request to the OData HTTP Web API service to retrieve a selected record. The final product to perform the Ajax GET will appear this way:



First let's create the MVC application as an web site:




Then add the CSS3 and javascript files  (you can learn the 1 minute Twitter Bootstrap installing instructions here) : always check that you have brought all required files:


Look at the Web API ODataController class, to see the GET(int) method we're going to use:



You can see that the Get() action method requires a "key" object , and returns a SingleResult<Note> object. We'll send the ID of the selected Note via Ajax, so create a new html file:


Add the references to the CSS3 Twitter Bootstrap files:



Then we add an input tag for selecting the ID of the record to retrieve:

Next, we append all the DOM elements for displaying all of the item's details, inside  a panel set according to  the Bootstrap classes design:


This is the markup to copy-paste:


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Details</title>
    <link href="Content/bootstrap.css" rel="stylesheet" />
    <link href="Content/bootstrap-theme.css" rel="stylesheet" />
</head>
<body>
    <div class="container">
        <div class="jumbotron" align="middle">
            <h1>OData Web API   Details Form</h1>
            <p>Ajax HTTP GET Form to show Details of an item</p>
            <p style="font: 900 11px Georgia;">By Carmel Shvartzman</p>           
            <p><a class="btn btn-default btn-lg" role="button">Learn more about OData Web API</a></p>
        </div>
        <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>
                        <div class="btn-msg col-md-12">
                            <br />
                            <input class="btn btn-default" type="submit" value="See Message Details" /><br />
                            <br />
                        </div>
                        <div class="alert alert-success message"></div>
                        <div class="alert alert-danger error"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>


After the markup, code the javascript, with the necessary references to the sources:

When the button is clicked, we fetch the ID of the record to be displayed.  Next we prepare the Ajax JSON request for OData as follows:

If the response is OK, we fill all fields with the data. Else, we show an error 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[type=submit]").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");
            }
        })
    </script>


The action method at the ODataController gets the ID as parameter, and returns the item:



Build & run the application.
Choose the ID of the item to retrieve. Now click the submit button to get the details for an item, sending an Ajax request in JSON format.
Then the web page will appear as follows: Provided the entered message ID exists, we get the details together with an OK message:


In case of an error, we get the error message:



That's all!!!!

In this post we've learned step by step how to build a web client which retrieves a record from a database by sending an HTTP GET request via Ajax to an WebAPI OData RESTful service implemented with the ODataController.
Enjoy coding.....

By Carmel Shvartzman

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


No comments:

Post a Comment