Getting Started With ASP.Net Web API 2: Day 4

Introduction

This is my fourth article on Web API 2. This article explains the Web API in a HTML page. This is the most simple task to consume in HTML using JavaScript. In my previous articles we saw MVC, then Web Forms.

In this article we will learn how to create an ASP.NET Web API 2 endpoint capable of handling HTML forms. We can create a controller action that accepts a model and that model will help to get and set the form value and ASP.NET Web API to do the model binding for us. 

  1. public class FormController : ApiController  
  2. {  
  3.     public UserModel Post(FormDataCollection form)  
  4.     {  
  5.         //process form...  
  6.   
  7.         var user = new UserModel  
  8.         {  
  9.              Email = form["Email"],  
  10.              Name = form["Name"],  
  11.              Address = form["Address"],  
  12.              Address2 = form["Address2"],  
  13.               Mobile = form["Mobile"]  
  14.         };  
  15.   
  16.             return user;  
  17.     }  
  18. }  

System.Net.Http.Formatting.FormDataCollection is used to handle the form as we need. 

When we submit the data form URL with the Web API it uses MediaTypeFormatter to extract data from the HttpRequestMessage and pass it to the relevant action selected to the handle the request. By default, the Web API reads the body of the request only once, so when using a model to bind to form data, that model should encapsulate all of the form fields. It is not possible to pass some of the fields as part of the request body and some in the URL and expect the framework to try to automatically reconcile them into a single model.

Prerequisites

There are the following things we need to use when developing a Web API 2 Application under the Web Form.

  • Visual Studio 2013
  • ASP.NET Web API

Getting Started

In this section we will follow some section and these are:

  • Create ASP.NET Web Form
  • Add Web API 2 Controller

Create ASP.NET Web API with MVC

There are some basic procedures to follow, when creating a Web API along with MVC using Visual Studio 2013, we need to also check the Web API button, as we are showing in the following images.

Step 1

Open the Visual Studio 2013 and click New Project.

Step 2

Select the ASP.NET Web Application and provide a nice name for the project.

ASPScreen

Step 3

Select the Web API template and click the OK button.

SelectWebAPI

Step 4

Add a UserModel class to the model where we define all the necessary fields. In the following image, I have defined some fields like name, email,  Address and Mobile number.

ModelClass

Step 5

Add the Form controller. When we create the Form Controller be sure we have used a model and the System.Net.Http.Formatting namesapce.

FormController

Step 6

Add the User Controller.

UserController

Step 7

Now make a HTML design.  Click on View and select Home folder, then we will get the default Index.Cshtml (Razaor) page.

  1. <div class="row">  
  2.     <div class="col-md-6">  
  3.         <h2>HTML form</h2>  
  4.         <div>  
  5.             <form role="form" method="post" action="/api/form" enctype="application/x-www-form-urlencoded">  
  6.                 <div class="form-group">  
  7.                     <label for="name">Name</label>  
  8.                     <input type="text" class="form-control" name="name" placeholder="Enter name">  
  9.                 </div>  
  10.                 <div class="form-group">  
  11.                     <label for="email">Email</label>  
  12.                     <input type="email" class="form-control" name="email" placeholder="Enter email">  
  13.                 </div>  
  14.                 <div class="form-group">  
  15.                     <label for="Address">Address</label>  
  16.                     <input type="text" class="form-control" name="Address" placeholder="Enter street Number">  
  17.                 </div>  
  18.                 <div class="form-group">  
  19.                     <label for="Address2">Address 2</label>  
  20.                     <input type="text" class="form-control" name="Address2" placeholder="Enter the state and country Name">  
  21.                 </div>  
  22.                 <div class="form-group">  
  23.                     <label for="Mobile">Mobile Number</label>  
  24.                     <input type="text" class="form-control" name="Mobile" placeholder="Enter Mobile Number">  
  25.                 </div>  
  26.                 
  27.                 <button type="submit" class="btn btn-default">Submit</button>  
  28.             </form>  
  29.         </div>  
  30.         <div>  
  31.             <br />  
  32.             <button id="postJS" class="btn btn-default">Post Data Using JavaScript</button>  
  33.         </div>  
  34.     </div>  
  35. </div>  
Description

@Section Script

This is the area where we use the JavaScript  and ajax to post the data.
  1. @section scripts {  
  2.     <script type="text/javascript">  
  3.         $(function () {  
  4.             $("#postJS").on("click"function () {  
  5.                 var data = {  
  6.                         name: $("input[name='name']").val(),  
  7.                         email: $("input[name='email']").val(),  
  8.                         Address: $("input[name='Address']").val(),  
  9.                         Address2: $("input[name='Address2']").val(),  
  10.                         Mobile: $("input[name='Mobile']").val(),  
  11.                 };  
  12.                 console.log(data);  
  13.                 $.ajax({  
  14.                     data: data,  
  15.                     datatype: "html",  
  16.                     type: "POST",  
  17.                     url: "/api/user"  
  18.                 }).done(function (res) {  
  19.                     alert(res.Email + " " + res.Name + " " + res.Address+" "+ res.Address2+" "+ res.Mobile);  
  20.                 });  
  21.             });  
  22.         });  
  23.     </script>  
  24. }  
Step 8

Build and press F5 to run the project.

Output As Input Screen

OutputBlank

Output

This is the output when we hit the submit button, this will show all the submitted data since we used console.log(data) using JavaScript.

OutputSubmit

After clicking the Post Data using the JavaScript Button, we can see the data in the alert box, using JavaScript.

OutputWebAPI

Summary

In this article we learned the basic procedure to consume the Web API in a HTML page. I hope the way I consumed the HTML page is the simplest way.

Further Reading

<< Getting Started with ASP.NET Web API 2 : Day 3

Up Next
    Ebook Download
    View all
    Learn
    View all