How To Post Data To WebAPI Using jQuery

Welcome to the next part of a tutorial in the WebAPI series. In this post, I am going to explain, how to post and save the user entered data in the database, using Web API service. If you are new to Web API in ASP.NET MVC5, please refer  to the posts given below for the basics of WebAPI.

  • Introduction to WebAPI.
  • How to fetch and display data from WebAPI in ASP.NET MVC5

Now, let's begin our tutorial:

Create Visual studio application

  1. Create a ASP.NET Web Application(Visual Studio 2013 or 2015), using Empty MVC template.
  2. It is a great idea to start any Application, using an empty template because there is more scope for learning and implementing every thing from scratch (not for production).
  3. Now, our solution contains basic MVC project structure.
  4. Add a database to the App_Data folder (by right click App_Data folder --> Add --> New Item --> Select SQL database, under Data section --> name it --> Add.
  5. Create a table in the database with the code, given below:
    1. CREATE TABLE [dbo].[Student] (  
    2. [StudentID] INT NOT NULL,  
    3. [StudentName] VARCHAR (50) NOT NULL,  
    4. [Email] VARCHAR (50) NOT NULL,  
    5. [City] VARCHAR (50) NULL,  
    6. [Contact] BIGINT NULL,  
    7. [Country] VARCHAR (50) NULL,  
    8. PRIMARY KEY CLUSTERED ([StudentID] ASC)  
    9. );  

Add ADO.NET Entity Data Model

  1. Right click on Models folder--> Add --> New Item -->Select ADO.NET Entity Data Model(Under Data) --> name it -->Add --> select Add from the database (In Entity Data Model wizard) --> Next.
  2. Select the database --> give name for web.config.
  3. Choose your database objects(tables) and click finish.
  4. Now, Model is added to my project.

    Note: Now, we have to create a WebAPI controller. For it, this article will help you to setup WebAPI in your Application Introduction to WebAPI in ASP.NET MVC 5.

Web api controller to Application

  1. Replace the code of WebAPI controller with the code, given below:
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Net;  
    5. using System.Net.Http;  
    6. using System.Web.Http;  
    7. using PostingDatainWebAPI.Models;  
    8. namespace PostingDatainWebAPI.Controllers {  
    9.     public class StudentAPIController: ApiController {  
    10.         public HttpResponseMessage Post(Student student) {  
    11.             HttpResponseMessage result;  
    12.             if (ModelState.IsValid) {  
    13.                 using(StudentDataBaseEntities db = new StudentDataBaseEntities()) {  
    14.                     db.Students.Add(student);  
    15.                     db.SaveChanges();  
    16.                 }  
    17.                 result = Request.CreateResponse(HttpStatusCode.Created, student);  
    18.             } else {  
    19.                 result = Request.CreateResponse(HttpStatusCode.BadRequest, "Server failed to save data");  
    20.             }  
    21.             return result;  
    22.         }  
    23.     }  
    24. }  

Create a User form page to input some data

  1. Here, client is a simple View page (Index .cshtml page from PostController).
  2. Create a Controller by right clicking on Controllers folder -->  name it as a PostController.
  3. I created an Index action method and added a view with Index.cshtml name.
    1. //Using Jquery  
    2. public ActionResult Index()  
    3. {  
    4.     return View();  
    5. }  
  4. In this View, I added a simple jQuery AJAX method to post the data to Web API Service.
  5. Replace the Index view code with the code, given below:
    1. @{  
    2. ViewBag.Title = "Posting Data to WEBAPI using Jquery";  
    3. }  
    4.   
    5.   
    6. <h3 class="text-info">Posting Data to WEBAPI using Jquery</h3>  
    7. <script src="~/Scripts/jquery-1.10.2.min.js"></script>  
    8. <style>  
    9. input{  
    10. max-width:250px;  
    11. }  
    12. </style>  
    13. <h5 class="text-danger">  
    14.     <b>Note:</b>Please Enter all details correctly and submit  
    15. Here i did not applied validations to this form  
    16. </h5>  
    17. <div class="container">  
    18.     <form name="postform" id="postform" class="form-horizontal">  
    19.         <div class="form-group">  
    20.             <label class="text-info">Student ID</label>  
    21.             <input type="number" id="txtStudentID" class="form-control" />  
    22.         </div>  
    23.         <div class="form-group">  
    24.             <label class="text-info">Student Name</label>  
    25.             <input type="text" id="txtStudentName" class="form-control" />  
    26.         </div>  
    27.         <div class="form-group">  
    28.             <label class="text-info">Email</label>  
    29.             <input type="email" id="txtEmail" class="form-control" />  
    30.         </div>  
    31.         <div class="form-group">  
    32.             <label class="text-info">City</label>  
    33.             <input type="text" id="txtCity" class="form-control" />  
    34.         </div>  
    35.         <div class="form-group">  
    36.             <label class="text-info">Contact Number</label>  
    37.             <input type="number" id="txtContact" class="form-control" />  
    38.         </div>  
    39.         <div class="form-group">  
    40.             <label class="text-info">Country</label>  
    41.             <input type="text" id="txtCountry" class="form-control" />  
    42.         </div>  
    43.         <button type="submit" class="btn btn-default">Save</button>  
    44.     </form>  
    45. </div>  
    46. <script type="text/javascript">  
    47. $(document).ready(function () {  
    48. $("#postform").submit(function (e) {  
    49. e.preventDefault();  
    50. var apiurl = "http://localhost:9627/api/StudentAPI";  
    51. var data = {  
    52. StudentID: $("#txtStudentID").val().trim(),  
    53. StudentName: $("#txtStudentName").val().trim(),  
    54. Email: $("#txtEmail").val().trim(),  
    55. City: $("#txtCity").val().trim(),  
    56. Contact: $("#txtContact").val().trim(),  
    57. Country: $("#txtCountry").val().trim(),  
    58. }  
    59. $.ajax({  
    60. url: apiurl,  
    61. type: 'POST',  
    62. dataType: 'json',  
    63. data: data,  
    64. success: function (d) {  
    65. alert("Saved Successfully");  
    66. document.getElementById("postform").reset();  
    67. },  
    68. error: function () {  
    69. alert("Error please try again");  
    70. }  
    71. });  
    72. });  
    73. });  
    74.   
    75. </script>  
    Note: For this form, I have not implemented client side validation.

  6. Here, I am reading the form values, using jQuery.and posting form values to Web API for saving on the database.
  7. The output of the Application is:
    output

  8. After saving the data on the Server, you will get a message like:

    output

    Download the source code of this Application here.. Source Code(Visual studio 2015 code).

Conclusion

I hope this tutorial is understandable and useful for every reader. If you are not subscribed to this blog, subscrib to it. See this tutorial in my blog.

Up Next
    Ebook Download
    View all
    Learn
    View all