Friday, September 12, 2014

Create an Ajax Web Client for OData Web API RESTful ODataController HTTP-POST JSON


In this article we build a web client which creates a new record in a database by sending an HTTP POST request via Ajax to an Web API OData RESTful service implemented with the ODataController. We'll build the form using the Twitter Bootstrap.

Our task here is to perform a POST request using the OData protocol in order to set the values of a new Entity.

We're using an OData Web API which we build in a previous Web API ODataController tutorial. Also you can find the details of installing the Twitter Bootstrap 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 have an Entity called "Note"   : we want to send a POST request to the OData HTTP Web API service to create a new record. Our final Form to perform the Ajax POST will show as follows:
Create an Ajax Web Client for OData Web API RESTful  ODataController HTTP-POST JSON


First of all, create the MVC application as an empty web site:




Then add the Twitter Bootstrap CSS3 and javascript files  (you can follow the 1 minute Twitter Bootstrap install instructions here) : check that you have all the required files:


Open the Web API ODataController class:


You can see that the Post() action method requires a "Note" object as parameter, returning an IHttpActionResult. We'll send that Note JSON object via Ajax, so make a new html file:


At the HEAD of the HTML file, add the references to the CSS3 Twitter Bootstrap files:


Then create the web Form to insert a new "Note" object, declaring the Bootstrap classes as follows:


Notice that we added two div to show messages: the divs will be hidden until they are necessary.
Here you have the HTML markup to copy-paste:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></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   Create Form</h1>
            <p>Building an Ajax HTTP POST Form to Create 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">
                <div class="text-muted">&nbsp;
                    <h2>Create New Message</h2>
                </div>&nbsp;    
            </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" value="Bender" 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" value="frygmail.com" 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" value="This is a reminder" 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" value="Remember we're meeting at 22:00 to watch Futurama..." class="form-control" />

                            </div>
                        </div>                         
                        <div> 
                            <div class="btn-msg col-md-12"><br /> 
                                <input class="btn btn-default" type="submit" value="Send Message" /><br /><br />                                
                            </div>
                            <div class="alert alert-success message">The Message was sent successfully!!!</div>
                            <div class="alert alert-danger error"></div>
                        </div>
                    </div>   
            </div>
        </div>  
    </div>


After the Form markup, add the javascript code to send the POST request:



Notice we refer the Bootstrap and jQuery javascript files first. Then we hide the message's divs, and inside the event handler for the submit button, we create a "Note" JSON object to be submitted to the OData web service.
Then we declare the $.ajax for create the HTTP POST request:


What we do here is to show the OK message if we get a successful response, or to show the error message if we didn't. Here you have 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 to = $("input[name=To]").val();
                var from = $("input[name=From]").val();
                var heading = $("input[name=Heading]").val();
                var body = $("input[name=Body]").val();
                var data = '{"To":"' + to + '","From":"' +
                    from + '","Heading":"' +
                    heading + '","Body":"' + body + '"}';

                $.ajax({
                    url: "http://localhost:6954/OData/Notes",
                    type: "POST",
                    data: data,
                    dataType: "json",
                    contentType: "application/json",
                    beforeSend: function (data) {
                        
                    },
                    success: function (data) {
                        
                        $("div.message").css("display", "block");
                    },
                    error: function (msg) {
                        var oError = JSON.parse(msg.responseText);
                        fnError("Error : " + oError.error.innererror.message);
                    }
                })
            });

            function fnError(msg) {
                $("div.error").html(msg);
                $("div.error").css("display", "block");
            }
        })
    </script>

Build & run the application, and click the submit button to create an Ajax request in JSON format:


Provided the entered data was legal input, we get the OK message:



Now we'll try to get an error: let's see the Data Annotations for the "Note" object:

The "From" field must be an Email. Then let's violate this condition:




At the Chrome Developer's Tools, open the "Network" tab and see the error 400 response we got:



The response includes the cause of the error and the name of the illegal field:



That's because our OData Web API checked the Model and found it no valid:




That's all!!!!

In this post we've seen step by step how to build a web client which creates a new record in a database by sending an HTTP POST request via Ajax to an Web API OData RESTful service implemented with the ODataController.
Enjoy coding.....

By Carmel Shvartzman

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



1 comment:

  1. The Asp.Net Mvc Club: Create An Ajax Web Client For Odata Web Api Restful Odatacontroller Http-Post Json >>>>> Download Now

    >>>>> Download Full

    The Asp.Net Mvc Club: Create An Ajax Web Client For Odata Web Api Restful Odatacontroller Http-Post Json >>>>> Download LINK

    >>>>> Download Now

    The Asp.Net Mvc Club: Create An Ajax Web Client For Odata Web Api Restful Odatacontroller Http-Post Json >>>>> Download Full

    >>>>> Download LINK

    ReplyDelete