How To Create WebAPI In ASP.NET MVC With C#

Introduction

This article demonstrates how to create and use an insert, update, and delete recored using Web APi in MVC with C# technology. Explain all HTTP methods like GET, PUT, DELETE and POST in this article.

What is web api?

ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework

What is CRUD ?

C-Create-POST
R - Read - GET
U - Update - PUT
D - Delete – DELETE

If your clients need data in multiple formats (json,xml,csv) the Wep Api needs minimal configuration compared to mvc. Wep Api returns data to the client according to content negotiation (if client needs xml it returns xml, if json, it returns json according to request header ) but in mvc you need more code to satisfy that. You have to explicitly specify data format when writing action methods.(JsonResult,ActionResult,XmlResult)

Wep Api gives you a more meaningful idea about what you are doing when you look at the code later. Comparing method signatures; public List<Student> Get() has more meaning than public JsonResult Index().

Step 1 - Create the new project in Visual Studio.

 

Then select the Web api from project template



Step 2

Create the new Database and table in SQL server. The database name is "PMS" and table name is "mst_Product"



Make sure product table ID is auto increment file (identity = true).

Now delete the areas folder and also the values controller in this created project



Step 3 - Add the model in this created project

Add the model in this project: right click on this model, add new items, then select data and choose the ado.net entity data model and assign the name of this model and click on ok button



Then choose the Eo designer from the database like this

Click on the next button, click on new connection and enter the server name; if local server then enter (Dot) otherwise write the server name

Click on ok button then enter the name of entity and click on next button



Then chooses Entity Famework 5.0 and also click on next button.



Expand the database and table and click on the check box for selecting this particular table

Then you should build the solution.

Step 4 - Add New API Controller in this project.

The right click on the controller and add new controller like this

API Controller

Add your controller name and also select the api controller with read/write actions, using entity framework

Then choose the model class which is based on your controller then choose the data context class (your model) then click on add button.

Now your product api controller code is automatically generated depending on your model
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Data;  
  4. using System.Data.Entity;  
  5. using System.Data.Entity.Infrastructure;  
  6. using System.Linq;  
  7. using System.Net;  
  8. using System.Net.Http;  
  9. using System.Web;  
  10. using System.Web.Http;  
  11. using Demo_WebApi.Models;  
  12. namespace Demo_WebApi.Controllers {  
  13.     public class ProductController: ApiController {  
  14.         private PMSEntities1 db = new PMSEntities1();  
  15.         // GET api/Product  
  16.         public IEnumerable < Mst_Product > GetMst_Product() {  
  17.             return db.Mst_Product.AsEnumerable();  
  18.         }  
  19.         // GET api/Product/5  
  20.         public Mst_Product GetMst_Product(int id) {  
  21.             Mst_Product mst_product = db.Mst_Product.Find(id);  
  22.             if (mst_product == null) {  
  23.                 throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));  
  24.             }  
  25.             return mst_product;  
  26.         }  
  27.         // PUT api/Product/5  
  28.         //PUT thant means Update the recored.  
  29.         public HttpResponseMessage PutMst_Product(int id, Mst_Product mst_product) {  
  30.             if (!ModelState.IsValid) {  
  31.                 return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);  
  32.             }  
  33.             if (id != mst_product.PID) {  
  34.                 return Request.CreateResponse(HttpStatusCode.BadRequest);  
  35.             }  
  36.             db.Entry(mst_product).State = EntityState.Modified;  
  37.             try {  
  38.                 db.SaveChanges();  
  39.             } catch (DbUpdateConcurrencyException ex) {  
  40.                 return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);  
  41.             }  
  42.             return Request.CreateResponse(HttpStatusCode.OK);  
  43.         }  
  44.         // POST api/Product  
  45.         //Post thant means Inset recored.  
  46.         public HttpResponseMessage PostMst_Product(Mst_Product mst_product) {  
  47.             if (ModelState.IsValid) {  
  48.                 db.Mst_Product.Add(mst_product);  
  49.                 db.SaveChanges();  
  50.                 HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, mst_product);  
  51.                 response.Headers.Location = new Uri(Url.Link("DefaultApi"new {  
  52.                     id = mst_product.PID  
  53.                 }));  
  54.                 return response;  
  55.             } else {  
  56.                 return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);  
  57.             }  
  58.         }  
  59.         // DELETE api/Product/5  
  60.         public HttpResponseMessage DeleteMst_Product(int id) {  
  61.             Mst_Product mst_product = db.Mst_Product.Find(id);  
  62.             if (mst_product == null) {  
  63.                 return Request.CreateResponse(HttpStatusCode.NotFound);  
  64.             }  
  65.             db.Mst_Product.Remove(mst_product);  
  66.             try {  
  67.                 db.SaveChanges();  
  68.             } catch (DbUpdateConcurrencyException ex) {  
  69.                 return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);  
  70.             }  
  71.             return Request.CreateResponse(HttpStatusCode.OK, mst_product);  
  72.         }  
  73.         protected override void Dispose(bool disposing) {  
  74.             db.Dispose();  
  75.             base.Dispose(disposing);  
  76.         }  
  77.     }  
  78. }  
Step 5 - Edit index view

Now go to the index page of home controller and paste this link for the jquery and also bootstrap js and css
  1. <!-- Latest compiled and minified CSS -->  
  2. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">  
  3. <!-- jQuery library -->  
  4. <script src="//code.jquery.com/jquery-1.12.4.js"></script>  
  5. <!-- Latest compiled JavaScript -->  
  6. <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>  
  7. <!-- add thids links for the error message-->  
  8. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/1.3.1/css/toastr.css" />  
  9. <script src="http://cdnjs.cloudflare.com/ajax/libs/toastr.js/1.3.1/js/toastr.js"></script>  
  10. <!--add this link for the datatable-->  
  11. <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />  

Now add the loader and style for the display loader and make a validation

  1. <style>  
  2.     .red_border {  
  3.         border: 1px solid #e46262;  
  4.     }  
  5.   
  6.     .LoadingDiv {  
  7.         top: 0;  
  8.         left: 0;  
  9.         position: fixed;  
  10.         opacity: 0.97;  
  11.         z-index: 10000000;  
  12.         background: Black;  
  13.         height: 100%;  
  14.         width: 100%;  
  15.         margin: auto;  
  16.     }  
  17.   
  18.     .dataTables_filter {  
  19.         float: right;  
  20.     }  
  21. </style>  
  22. <div id="dvLoader" class="LoadingDiv" style="display: none;">  
  23.     <table style="height: 100%; margin: auto;">  
  24.         <tr>  
  25.             <td style="vertical-align: middle;">  
  26.                 <center> <img src="http://www.girlsgotit.org/images/ajax-loader.gif" alt="Loading" /> </center>  
  27.             </td>  
  28.         </tr>  
  29.     </table>  
  30. </div>  
Now the add code of your html part for calling your service , when I click on a particular method then it calls this method
  1. <div id="body">  
  2.     <section class="content-wrapper main-content clear-fix">  
  3.         <h3>CRUD Opration Using Web APi</h3> you want to call this service then you should click on this particular service  
  4.         <ol class="round">  
  5.             <li class="one">  
  6.                 <h5><a style="cursor: pointer" data-toggle="modal" data-target="#AddProduct_Model">Add Product</a></h5> In this Api have three parameter for the insert recored. in this service ajax call type:POST </li>  
  7.             <li class="two">  
  8.                 <h5><a id="GetAllProduct" style="cursor: pointer">Get All Product</a></h5> this service has no any paramer call this serviec in url like this:<b> api/product</b> in this service ajax call type:GET </li>  
  9.             <li class="three">  
  10.                 <h5><a id="GetAllProductbyid" style="cursor: pointer">Get Product by Id</a></h5> this service has no any paramer call this serviec in url like this:<b> api/product/5</b> </li>  
  11.             <li class="four">  
  12.                 <h5><a data-toggle="modal" data-target="#UpdateProduct_Model" style="cursor: pointer">Update Product By Id</a></h5> this service has three parameter call this serviec in url like this:<b> api/product/5</b> in this service ajax call type:PUT </li>  
  13.             <li class="five">  
  14.                 <h5><a id="DeleteProduct" style="cursor: pointer">Delete Product By Id</a></h5> this service has one parameter call this serviec in url like this:<b> api/product/5</b> in this service ajax call type:DELETE </li>  
  15.         </ol>  
  16.     </section>  
  17. </div>  
Step 6 - POST Method

Now create the model for the insert recorded using POST method

  1. <!-- Modal add product -->  
  2. <div id="AddProduct_Model" class="modal fade" role="dialog">  
  3.     <div class="modal-dialog">  
  4.         <!-- Modal content-->  
  5.         <div class="modal-content">  
  6.             <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">×</button>  
  7.                 <h4 class="modal-title">Add Product</h4>  
  8.             </div>  
  9.             <div class="modal-body"> Product Name :<input type="text" id="txtName" class="form-control required" /> Product Description :<textarea id="txtDesc" class="form-control required"></textarea> Product Price :<input type="text" id="txtPrice" onkeypress="return isNumberKey(event)" class="form-control required" /> </div>  
  10.             <div class="modal-footer"> <button type="button" class="btn btn-success" id="btnSave">Save</button> <button type="button" class="btn btn-danger" onclick="clear();" data-dismiss="modal">Close</button> </div>  
  11.         </div>  
  12.     </div>  
  13. </div> 
Model saves button click then call my POST method,
  1. $("#btnSave").click(function() {  
  2.     debugger  
  3.     var PID = 0;  
  4.     var Name = $("#txtName").val();  
  5.     var Desc = $("#txtDesc").val();  
  6.     var Price = parseFloat($("#txtPrice").val()).toFixed(2);  
  7.     if (CheckRequiredFields()) {  
  8.         $('#dvLoader').show();  
  9.         $.ajax({  
  10.             url: '@Url.Action("Product", "Api")',  
  11.             type: 'POST',  
  12.             data: JSON.stringify({  
  13.                 "PID": parseInt(PID),  
  14.                 "Name": Name,  
  15.                 "Description": Desc,  
  16.                 "price": Price  
  17.             }),  
  18.             dataType: "json",  
  19.             contentType: "application/json; charset=utf-8",  
  20.             success: function(result) {  
  21.                 $('#dvLoader').hide();  
  22.                 jQuery.noConflict();  
  23.                 $('#AddProduct_Model').modal('hide');  
  24.                 toastr.success("product insert successfull");  
  25.                 clear();  
  26.             }  
  27.         });  
  28.     }  
  29. });  
Now see the output of POST method


Step 7 - GET Method.


Add the model for the display of all inserted product data in json and xml format,
  1. <!-- Show product Data-->  
  2. <div id="GetData" class="modal fade" role="dialog">  
  3.     <div class="modal-dialog">  
  4.         <!-- Modal content-->  
  5.         <div class="modal-content">  
  6.             <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">×</button>  
  7.                 <h4 class="modal-title">Show Product Data</h4>  
  8.             </div>  
  9.             <div class="modal-body">  
  10.                 <p id="idjson"></p>  
  11.             </div>  
  12.             <div class="modal-footer"> <a style="float: left; color: #3791cc" href="api/product">click hear to show xml response.</a> <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button> </div>  
  13.         </div>  
  14.     </div>  
  15. </div>  
Now call the Get method for showing json and xml data of product table
  1. $("#GetAllProduct").click(function() {  
  2.     $.ajax({  
  3.         url: '@Url.Action("Product", "Api")',  
  4.         type: 'GET',  
  5.         // data: JSON.stringify({ }),  
  6.         dataType: "json",  
  7.         contentType: "application/json; charset=utf-8",  
  8.         success: function(result) {  
  9.             jQuery.noConflict();  
  10.             $("#idjson").text(JSON.stringify(result));  
  11.             $('#GetData').modal('show');  
  12.         }  
  13.     });  
  14. });  
Now see the output of GET method

Now add the model for displaying json and xml data for the particular product Id

  1. <!-- Show product Data by Id-->  
  2. <div id="GetDatabyid" class="modal fade" role="dialog">  
  3.     <div class="modal-dialog">  
  4.         <!-- Modal content-->  
  5.         <div class="modal-content">  
  6.             <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">×</button>  
  7.                 <h4 class="modal-title">Show Product Data by ID</h4>  
  8.             </div>  
  9.             <div class="modal-body">  
  10.                 <p id="idjsonbyid"></p>  
  11.             </div>  
  12.             <div class="modal-footer"> <a style="float: left; color: #3791cc" href="api/product/5">click hear to show xml response by id.</a> <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button> </div>  
  13.         </div>  
  14.     </div>  
  15. </div>  
Now add the method of the GET for the particular product id
  1. $("#GetAllProductbyid").click(function() {  
  2.     $.ajax({  
  3.         url: 'api/product/5',  
  4.         type: 'GET',  
  5.         dataType: "json",  
  6.         contentType: "application/json; charset=utf-8",  
  7.         success: function(result) {  
  8.             jQuery.noConflict();  
  9.             $("#idjsonbyid").text(JSON.stringify(result));  
  10.             $('#GetDatabyid').modal('show');  
  11.         }  
  12.     });  
  13. });  
Now show the output of get method with particular product id

 

Step 8 - PUT Method.

Now add the model for the updated product

  1. <!-- Modal Update product -->  
  2. <div id="UpdateProduct_Model" class="modal fade" role="dialog">  
  3.     <div class="modal-dialog">  
  4.         <!-- Modal content-->  
  5.         <div class="modal-content">  
  6.             <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">×</button>  
  7.                 <h4 class="modal-title">Update Product of ID 5</h4>  
  8.             </div>  
  9.             <div class="modal-body"> Product Name :<input type="text" id="txtName2" class="form-control " /> Product Description :<textarea id="txtDesc2" class="form-control "></textarea> Product Price :<input type="text" id="txtPrice2" onkeypress="return isNumberKey(event)" class="form-control " /> </div>  
  10.             <div class="modal-footer"> <button type="button" class="btn btn-success" id="btnUpdate">Update</button> <button type="button" class="btn btn-danger" onclick="clear();" data-dismiss="modal">Close</button> </div>  
  11.         </div>  
  12.     </div>  
  13. </div>  
Now add the PUT Method for the updated particular product by the product Id.
  1. $("#btnUpdate").click(function() {  
  2.             var PID = 5;  
  3.             var Name = $("#txtName2").val();  
  4.             var Desc = $("#txtDesc2").val();  
  5.             var Price = parseFloat($("#txtPrice2").val()).toFixed(2);  
  6.             $('#dvLoader').show();  
  7.             $.ajax({  
  8.                 url: 'api/product/5',  
  9.                 type: 'PUT',  
  10.                 data: JSON.stringify({  
  11.                     "PID": parseInt(PID),  
  12.                     "Name": Name,  
  13.                     "Description": Desc,  
  14.                     "price": Price  
  15.                 }),  
  16.                 dataType: "json",  
  17.                 contentType: "application/json; charset=utf-8",  
  18.                 success: function(result) {  
  19.                     $('#dvLoader').hide();  
  20.                     $('#UpdateProduct_Model').modal('hide');  
  21.                     toastr.success("product updated successfully.");  
  22.                     clear2();  
  23.                 }  
  24.             });  

 

Now see the updated product output of product of ID  5



Step 9 - DELETE Method.

Now add the method for the deleted product by the particular product Id.

  1. $("#DeleteProduct").click(function() {  
  2.             $.ajax({  
  3.                 url: 'api/product/5',  
  4.                 method: 'DELETE',  
  5.                 contentType: 'application/json',  
  6.                 success: function(result) {  
  7.                     toastr.success("product Deleted successfull");  
  8.                 },  
  9.                 error: function(request, msg, error) {  
  10.                     // handle failure  
  11.                 }  
  12.             });  
Now add the four functions used for validation and clear the text field value
  1. function CheckRequiredFields() {  
  2.     var isValid = true;  
  3.     $('.required').each(function() {  
  4.         if ($.trim($(this).val()) == '') {  
  5.             isValid = false;  
  6.             $(this).addClass('red_border');  
  7.         } else {  
  8.             $(this).removeClass('red_border');  
  9.         }  
  10.     });  
  11.     return isValid;  
  12. }  
  13.   
  14. function clear() {  
  15.     $("#txtName").val("");  
  16.     $("#txtDesc").val("");  
  17.     $("#txtPrice").val("");  
  18. }  
  19.   
  20. function clear2() {  
  21.     $("#txtName2").val("");  
  22.     $("#txtDesc2").val("");  
  23.     $("#txtPrice2").val("");  
  24. }  
  25.   
  26. function isNumberKey(evt) {  
  27.     var charcode = (evt.which) ? evt.which : evt.keycode  
  28.     if (charcode > 31 && (charcode < 48 || charcode > 58) && evt.keyCode != 35 && evt.keyCode != 36 && evt.keyCode != 37 && evt.keyCode != 38 && evt.keyCode != 39 && evt.keyCode != 40 && evt.keyCode != 46) {  
  29.         return false;  
  30.     } else {  
  31.         return true;  
  32.     }  
  33. }  

 

NOW see the OUTPUT of all PROJECTS,

If you want to download the code of my project then go to GitHub click here to download.

Up Next
    Ebook Download
    View all
    Learn
    View all