a blog for those who code

Thursday 2 February 2017

How to accept a HTML Form in Asp.Net Web API

In this post we will be discussing about how to accept a HTML form in Asp.Net Web API. What we want to do is to create an Asp.Net Web API endpoint that is capable of handling HTML forms. Today it is a very common requirement to submit HTML form data when building web applications.

Just take an example of Contact Form as shown below, where you have to accept the Name, Email and Message, thus through our Asp.Net Web API we will be creating an endpoint that handles the form to get Name, Email and Message.

If you want to learn more about Asp.Net Web API, start here Getting Started with Asp.Net Web API.


As you all know Asp.Net Web API uses MediaTypeFormatter's to extract data from HttpRequestMessage. Thus we have FormUrlEncodedMediaTypeFormatter which is capable of handling HTML forms (known as application/x-www-form-urlencoded). We will be using System.Net.Http.Formatting.FormDataCollection to get the form data as a key-value collection, and then manually handle the form.


Code Example


<body>
 <form role="form" method="post" action="/api/HtmlData" enctype="application/x-www-form-urlencoded">
  <div class="container">
   <div class="form-group">
    <label for="name">Name</label>
    <input type="text" class="form-control" name="name" placeholder="Enter ame" />
   </div>
   <div class="form-group">
    <label for="email">Email</label>
    <input type="text" class="form-control" name="email" placeholder="Enter email" />
   </div>
   <div class="form-group">
    <label for="message">Message</label>
    <textarea class="form-control" name="message" placeholder="Enter message"></textarea>
   </div>
   <button id="submitdata" type="submit" class="btn btn-default">Submit</button>
  </div>
 </form>
 <script type="text/javascript">
  $(function () {
   $("#submitdata").on("click", function () {
    var data = {
      name: $("input[name='name']").val(),
      email: $("input[name='email']").val(),
      message: $("input[name='message']").val(),
    };
    $.ajax({
      data: data,
      datatype: "html",
      type: "POST",
      url: "/api/HtmlData"
    }).done(function (res) {
// Success Message
    })
   })
  })
 </script>
</body>

Controller :


using System.Web.Http;
using System.Net.Http.Formatting;

namespace WebApi1.Controllers
{
 public class HtmlDataController : ApiController
 {
  public void Post(FormDataCollection data)
  {
   var contact = new ContactModel
   {
    Name = data["name"],
    Email = data["email"],
    Message = data["message"]
   };
  }
  public class ContactModel
  {
   public string Name { get; set; }
   public string Email { get; set; }
   public string Message { get; set; }
  }
}

Check the Result


Please Like and Share the CodingDefined Blog, if you find it interesting and helpful.

No comments:

Post a Comment