Sending HTML Form Data in ASP.Net Web API

Introduction

In this article, you will learn about  Send the HTML Form Data by using ASP. NET web API. The method of HTML is specified how to send form data, the form data is sent to page specified in the action attribute. The HTML forms is used two methods for sending the data to the server that are GET and Post Methods.

GET method

  • It appends the data into the URL in name /values pairs.
  • The Get method is used for only sending the nonsecure data. such as query string in Google.
  • The length of URL is limited.
  • It is useful for submissions where the user want to bookmarks the result.

POST method

  • It is useful for appending the data inside the body of the HTTP request.
  • There is no Size limitations of the URL.
  • It can not be bookmarked when we use the POST method for the Submission form.

For creating this application follow this procedure.

Step 1

Create the Web API application.

  • Start Visual Studio 2012.
  • Select "File"->"New"->"Project".
  • On the template window select "Installed" -> "Template" -> "Other Languages" -> "Visual C#" -> "Web".
  • Now choose "ASP. NET MVC4 Web Application" and change the name to "CodeHtml".
  • Click on the "OK" button.

    htm1.jpg

    Now a New ASP .NET MVC4 Project window is opened, then:

    12345.jpg
  • In this window select the "Web API".
  • And click on the "OK" button.

Step 2

Create the Model Class

  • In "Solution Explorer" Right click on "Model Folder"->"Add"->"Class".

    htm2.jpg
  • In "template window" select "Installed"->"Visual C#".
  • Choose "Class" change its name as "Change".
  • Click on "OK" button.

    htm6.jpg

Write this code in the "Model class" "Change.cs"

  1. namespace CodeHtml.Models  
  2. {  
  3.     using System;  
  4.     using System.ComponentModel.DataAnnotations;  
  5.     public class Change  
  6.     {  
  7.         [Required]  
  8.         [MaxLength(140)]  
  9.         public string Type { getset; }  
  10.         public DateTime Date { getset; }  
  11.     }  
  12. }

Step 3

Create the "Controller" Class

  • In the "Solution Explorer" right click on the "Controller Folder"->"Add"->"Controller".

    htm3.jpg
  • In "Controller" window Change the name of Controller.
  • In template choose "Empty API Controller".

    htm5.jpg

Write this code in the "ChangesController" class.

  1. namespace CodeHtml.Controllers  
  2. {  
  3.     using System;  
  4.     using System.Collections.Generic;  
  5.     using System.Net;  
  6.     using System.Net.Http;  
  7.     using System.Web;  
  8.     using System.Web.Http;  
  9.     using  CodeHtml.Models;  
  10.     public class ChangesController : ApiController  
  11.     {  
  12.         static readonly Dictionary<Guid, Change> changes = new Dictionary<Guid, Change>();  
  13.         [HttpPost]  
  14.         [ActionName("Code")]  
  15.         public HttpResponseMessage PostComplex(Change change)  
  16.         {  
  17.             if (ModelState.IsValid && change != null)  
  18.             {  
  19.                 change.Type = HttpUtility.HtmlEncode(change.Type);  
  20.                 var Id = Guid.NewGuid();  
  21.                 changes[Id] = change;  
  22.                 var response = new HttpResponseMessage(HttpStatusCode.Created)  
  23.                 {  
  24.                     Content = new StringContent(change.Type)  
  25.                 };  
  26.                 response.Headers.Location = new Uri(Url.Link("DefaultApi"new { action = "type", Id = Id }));  
  27.                 return response;  
  28.             }  
  29.             else  
  30.             {  
  31.                 return Request.CreateResponse(HttpStatusCode.BadRequest);  
  32.             }  
  33.         }  
  34.         [HttpPost]  
  35.         [ActionName("Decode")]  
  36.         public HttpResponseMessage PostSimple([FromBody] string value)  
  37.         {  
  38.             if (value != null)  
  39.             {  
  40.                 Change change = new Change()  
  41.                 {  
  42.                     Type = HttpUtility.HtmlEncode(value),  
  43.                     Date = DateTime.UtcNow  
  44.                 };  
  45.                 var Id = Guid.NewGuid();  
  46.                 changes[Id] = change;  
  47.                 var response = new HttpResponseMessage(HttpStatusCode.Created)  
  48.                 {  
  49.                     Content = new StringContent(change.Type)  
  50.                 };  
  51.                 response.Headers.Location = new Uri(Url.Link("DefaultApi"new { action = "type", Id = Id }));  
  52.                 return response;  
  53.             }  
  54.             else  
  55.             {  
  56.                 return Request.CreateResponse(HttpStatusCode.BadRequest);  
  57.             }  
  58.         }  
  59.         [HttpGet]  
  60.         public Change Type(Guid Id)  
  61.         {  
  62.             Change change;  
  63.             if (changes.TryGetValue(Id, out change))  
  64.             {  
  65.                 return change;  
  66.             }  
  67.             else  
  68.             {  
  69.                 throw new HttpResponseException(HttpStatusCode.NotFound);  
  70.             }  
  71.         }  
  72.     }  
  73. }   

Step 4

Write the code in the "Index.cshtml" file. The file is found in.

  • In the "Solution Explorer" .
  • IN "View folder"->"Home"->"Index.cshtml".

    htm4.jpg

Write this code in the "Index.cshtml".

  1. @section Scripts {  
  2.  <script type="text/javascript">  
  3.      $("#form1").submit(function () {  
  4.          var Serial = $.post('api/changes/code', $('#form1').serialize())  
  5.              .success(function () {  
  6.                  var path = Serial.getResponseHeader('Location');  
  7.                  var i = $('<a/>', { href: path, text: path });  
  8.                  $('#message').html(i);  
  9.              })  
  10.              .error(function () {  
  11.                  $('#message').html("Error for changes.");  
  12.              });  
  13.          return false;  
  14.      });  
  15.      $('#form2').submit(function () {  
  16.          var Serial = $.post('api/changes/decode', { "": $('#type1').val() })  
  17.              .success(function () {  
  18.                  var path = Serial.getResponseHeader('Location');  
  19.                  var i = $('<a/>', { href: path, text: path });  
  20.                  $('#message').html(i);  
  21.              })  
  22.              .error(function () {  
  23.                  $('#message').html("Error for changes.");  
  24.              });  
  25.          return false;  
  26.      });  
  27. </script>  
  28. }  
  29. <header>  
  30.     <div class="content-wrapper">  
  31.         <div class="float-left">  
  32.             <p class="site-title">  
  33.                 <a href="~/">HTML Form Data</a></p>  
  34.         </div>  
  35.     </div>  
  36. </header>  
  37. <div id="body">  
  38.     <section class="content-wrapper main-content clear-fix">  
  39.     <h1>Data with Date</h1>  
  40.     <form id="form1" method="post" action="api/changes/code"  
  41.         enctype="application/x-www-form-urlencoded">  
  42.         <div>  
  43.         <label for="type">Code</label>  
  44.         </div>  
  45.         <div>  
  46.         <input name="type" type="text" />  
  47.         </div>  
  48.         <div>  
  49.         <label for="date">Date</label>  
  50.         </div>  
  51.         <div>  
  52.         <input name="date" type="text" />  
  53.         </div>  
  54.         <div>  
  55.         <input type="submit" value="Submit" />  
  56.         </div>  
  57.     </form>  
  58.     <h1>Data without Date</h1>  
  59.     <form id="form2">  
  60.         <div>  
  61.             <label for="type">Decode</label>  
  62.         </div>  
  63.         <div>  
  64.             <input id="type1" type="text" />  
  65.         </div>  
  66.         <div>  
  67.             <input type="submit" value="Submit" />  
  68.         </div>  
  69.     </form>  
  70.     <h3 id="message" />  
  71.     </section>  
  72. </div> 
Step 5

Change the following code in the "WebApiConfig.cs" file. 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web.Http;  
  5. namespace wpfWebAPi  
  6. {  
  7.     public static class WebApiConfig  
  8.     {  
  9.         public static void Register(HttpConfiguration config)  
  10.         {  
  11.             config.Routes.MapHttpRoute(  
  12.                 name: "DefaultApi",  
  13.                 routeTemplate: "api/{controller}/{id}",  
  14.                 defaults: new { id = RouteParameter.Optional }  
  15.             );  
  16.         }  
  17.     }  
  18. } 

Output

Execute the application Press F5
 
htmout.jpg

Insert the data into the Textboxes.

htmout1.jpg

When the user clicks on the Submit Button then the action is performed and the browser sends the HTTP request and generates a URL.

htmout2.jpg

When the URL is clicked it shows the data that is inserted by the user.

htmout3.jpg

It generates by default the current Date.

htmout4.jpg