In this blog, we will see how to create a Web API in Visual Studio 2017 and consume this API from MVC application using jQuery.
Web API is the Microsoft open source technology for developing REST services based on HTTP protocol. ASP.Net Web API is a framework for building, consuming HTTP based service. The advantage of Web API is that it can be consumed by a wide range of clients like a web browser and mobile applications.
If you are new to Web API, then please read my earlier blog – ASP.Net Web API Tutorial
You might have created ASP.Net Web API projects and tested this API using a tool like postman. But here we will call API from MVC view page using JQuery code.
Let’s start the implementation by creating an empty project in Visual Studio 2017.
Select MVC and Web API as shown in below screen.
If you don’t want to create an empty project, then select Web API project and Add folders and core references for MVC.
Once your Web API or Empty project is ready, add ADO.NET Entity Data Model.
Select Model class from Dropdown.
Your API controller code will look like this.
namespace WebApiPractice.Controllers { public class ProductMastersController : ApiController { private ReviewAndShareEntities db = new ReviewAndShareEntities(); // GET: api/ProductMasters public IQueryable<ProductMaster> GetProductMasters() { return db.ProductMasters; } // GET: api/ProductMasters/5 [ResponseType(typeof(ProductMaster))] public IHttpActionResult GetProductMaster(int id) { ProductMaster productMaster = db.ProductMasters.Find(id); if (productMaster == null) { return NotFound(); } return Ok(productMaster); } // PUT: api/ProductMasters/5 [ResponseType(typeof(void))] public IHttpActionResult PutProductMaster(int id, ProductMaster productMaster) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (id != productMaster.id) { return BadRequest(); } db.Entry(productMaster).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!ProductMasterExists(id)) { return NotFound(); } else { throw; } } return StatusCode(HttpStatusCode.NoContent); } // POST: api/ProductMasters [ResponseType(typeof(ProductMaster))] public IHttpActionResult PostProductMaster(ProductMaster productMaster) { if (!ModelState.IsValid) { return BadRequest(ModelState); } db.ProductMasters.Add(productMaster); db.SaveChanges(); return CreatedAtRoute(“DefaultApi”, new { id = productMaster.id }, productMaster); } // DELETE: api/ProductMasters/5 [ResponseType(typeof(ProductMaster))] public IHttpActionResult DeleteProductMaster(int id) { ProductMaster productMaster = db.ProductMasters.Find(id); if (productMaster == null) { return NotFound(); } db.ProductMasters.Remove(productMaster); db.SaveChanges(); return Ok(productMaster); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } private bool ProductMasterExists(int id) { return db.ProductMasters.Count(e => e.id == id) > 0; } } } |
Now run your application by pressing F5 and set the URL format like this –
Accessing above URL will give you below result.
Add a view and write below code.
<script src=”~/Scripts/jquery-1.10.2.min.js”></script> <h2>Index</h2> <input type=”button” id=”btnGetProducts” value=”Product List” /> <script> $(“#btnGetProducts”).click(function () { $.getJSON(“/api/ProductMasters/”, function (data) { $.each(data, function (key, val) { console.log(val); }); }); }); </script> |
Once you click on the Product List button, you may see the result in the console by pressing F12 in Google Chrome, result will be in json format.
You can display the result in HTML elements or in an alert.
To display the product name only, you may use val.product as shown in below snippet.
<script> $(“#btnGetProducts”).click(function () { $.getJSON(“/api/ProductMasters/”, function (data) { $.each(data, function (key, val) { console.log(val.product); }); }); }); </script> |
<script> $(“#btnGetProducts”).click(function () { $.getJSON(“/api/ProductMasters/”, function (data) { $.each(data, function (key, val) { console.log(val.product + ” “ + val.cost + ” “ + val.stock); }); }); }); </script> |
$(“#btnGetById”).click(function () { $.getJSON(“/api/ProductMasters/1”, function (data) { console.log(data.product + ” “ + data.cost + ” “ + data.stock); }); }); |
$(“#btnAdd”).click(function () { var productMaster = “{product:’Lenovo’, cost:’18700′,stock:’26’}”; $.ajax({ type: “POST”, contentType: “application/json,charset=utf-8”, url: “/api/ProductMasters/”, data: JSON.stringify(productMaster), success: function (res) { alert(‘pass’); }, error: function (request, message, error) { alert(‘error’); } }); }); |
$(“#btnDeleteByID”).click(function () { var id = 5; $.ajax({ type: “delete”, contentType: “application/json,charset=utf-8”, url: “/api/ProductMasters/” + id, data: {}, success: function () { alert(‘Success’); }, error: function (request, message, error) { alert(‘Error’); } }); }); |
Below sample code to call update API to update a record where id is 4.
$(“#btnUpdate”).click(function () { var id = 4; var products = “{product:’Lenovo’, cost:’18700′,stock:’26’}”; $.ajax({ type: “put”, contentType: “application/json,charset=utf-8”, url: “/api/ProductMasters/” + id, data: JSON.stringify(products), success: function (res) { alert(‘pass’); }, error: function (request, message, error) { alert(‘error’); } }); }); |
Hope you like this.
Please share this on facebook and twitter.
Comment below, in case of any query.
Other blogs to read –
LINQ with an MVC Project
Interview Questions and Answers Series