Getting Started With ASP.NET Core And jQuery CRUD Using WEB API

ASP.NET Core

Introduction

In this session, we will learn,

  • How to consume Employee in-memory database using EmployeeRepository.
  • How to create ASP.NET Core custom API controller with CRUD operations.
  • Getting List of Objects
  • Create a new insert item
  • Update an Item
  • Delete an Item 
  • Write HttpPost Create API method.
  • Write HttpPut Update API method.
  • Write HttpPost Delete API method.
  • Route table
  • Set start controller Route to Home Index method.
  • jQuery/HTML pass table row value to a JavaScript function
  • jQuery Ajax HttpGet
  • jQuery Ajax HttpPut
  • jQuery Ajax HttpPost
  • Editable HTML table 
  • Responsive Web Design
  • A lab exercise for you to demonstrate what have you learned from this training material to create your own Todo CRUD operation using TodoRepository included in this training material.

Prerequisites

To be able to run the example from the download or to build it from scratch, you need to have the following tools.

  • Visual Studio 2017 or above 
  • .NET Core 2.0 or above
  • jQuery

Create a new solution and name it as WebApiAspNetCoreJQuerySolution.

ASP.NET Core

Add a new ASP.NET Core Web Application project and name it as EmployeeJquery.Ui.

ASP.NET Core

On the next screen, select Web API project template.

ASP.NET Core

Compile and run the application and we’ll see the home page.

ASP.NET Core

We want to create the below single page application with CRUD operations - Add, Update, and Remove functionality with in-memory EmployeeRepository Database.

ASP.NET Core

We need to perform the below tasks.

  • Set EmployeeRepository
  • Create EmployeeController
  • Add Home Index page - Creating a Client by Using jQuery Ajax
  • Update API routing to go Home page.
  • Create updateable HTML table and code jQuery AJAX Http Calls
Set TodoRepository

Use SmartIT.Employee.MockDB which has TodoRepository in it with the in-memory MOCK database. You may go to the below website and read the usage examples.

https://www.nuget.org/packages/SmartIT.Employee.MockDB/

Use NuGet Package Manager to install SmartIT.Employee.MockDB from nugget.org.

ASP.NET Core

Create EmployeeController

In the Controllers directory, add a new Web API controller Class and Add.

ASP.NET Core 

EmployeeController will be created.

  1. namespace EmployeeJquery.Ui.Controllers  
  2. {  
  3.     [Route("api/[controller]")]  
  4.     public class EmployeeController : Controller  
  5.     {  
  6.         // GET: api/values  
  7.         [HttpGet]  
  8.         public IEnumerable<string> Get()  
  9.         {  
  10.             return new string[] { "value1""value2" };  
  11.         }  
  12.   
  13.         // GET api/values/5  
  14.         [HttpGet("{id}")]  
  15.         public string Get(int id)  
  16.         {  
  17.             return "value";  
  18.         }  
  19.   
  20.         // POST api/values  
  21.         [HttpPost]  
  22.         public void Post([FromBody]string value)  
  23.         {  
  24.         }  
  25.   
  26.         // PUT api/values/5  
  27.         [HttpPut("{id}")]  
  28.         public void Put(int id, [FromBody]string value)  
  29.         {  
  30.         }  
  31.   
  32.         // DELETE api/values/5  
  33.         [HttpDelete("{id}")]  
  34.         public void Delete(int id)  
  35.         {  
  36.         }  
  37.     }  
  38. }  
Replace the EmployeeController code with the below code which has all the APIs for CRUD operation.
  1. using System.Collections.Generic;  
  2. using Microsoft.AspNetCore.Mvc;  
  3. using SmartIT.Employee.MockDB;  
  4.   
  5. namespace EmployeeJquery.Ui.Controllers  
  6. {  
  7.   [Produces("application/json")]  
  8.   [Route("api/Employee")]  
  9.   public class EmployeeController : Controller  
  10.   {  
  11.   
  12.     private EmployeeRepository db = new EmployeeRepository();  
  13.   
  14.     [Route("~/api/GetEmployees")]  
  15.     [HttpGet]  
  16.     public ICollection<Employee> GetEmployees()  
  17.     {  
  18.       return db.GetAll();  
  19.     }  
  20.   
  21.     [HttpGet("{id}")]  
  22.     public Employee Get(int id)  
  23.     {  
  24.       return db.FindbyId(id);  
  25.     }  
  26.   
  27.     [Route("~/api/AddEmployee")]  
  28.     [HttpPost]  
  29.     public IActionResult AddEmployee([FromBody]Employee obj)  
  30.     {  
  31.       db.Add(obj);  
  32.       return new ObjectResult("Employee added successfully!");  
  33.     }  
  34.   
  35.     [Route("~/api/UpdateEmployee")]  
  36.     [HttpPut]  
  37.     public IActionResult UpdateEmployee([FromBody]Employee obj)  
  38.     {  
  39.       db.Update(obj);  
  40.       return new ObjectResult( "Employee modified successfully!");  
  41.     }  
  42.   
  43.     [Route("~/api/DeleteEmployee/{id}")]  
  44.     [HttpDelete]  
  45.     public IActionResult Delete(int id)  
  46.     {  
  47.       db.Delete(db.FindbyId(id));  
  48.       return new ObjectResult("Employee deleted successfully!");  
  49.     }  
  50.   }  
  51. }  
Compile and run the application.

Test GetEmployees with calling to API

http://localhost:60769/api/GetEmployees

Note

Your port number may be different than ours, use your local port number.

ASP.NET Core

Creating a Client by Using jQuery Ajax

Add an MVC Controller Class in Controller directory.

ASP.NET Core

A HomeController will be created ike below.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5. using Microsoft.AspNetCore.Mvc;  
  6.   
  7. // For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860  
  8.   
  9. namespace EmployeeJquery.Ui.Controllers  
  10. {  
  11.     public class HomeController : Controller  
  12.     {  
  13.         // GET: /<controller>/  
  14.         public IActionResult Index()  
  15.         {  
  16.             return View();  
  17.         }  
  18.     }  
  19. }  

Add 2 directory under Controller Views and Home like below.

ASP.NET Core

Add an MVC View Page on the Home directory like below.

ASP.NET Core

An empty Index.cshtml will be created like below.

  1. @*  
  2.     For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860  
  3. *@  
  4. @{  
  5. }  
  6.   
  7. @*  
  8.     For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860  
  9. *@  
  10. @{  
  11. }  
  12. SmartIT by John Kocer  
Update API routing to go Home page.

Add a route into Startup.cs page’s  Configure method for the  HomeController like below.

  1. public void Configure(IApplicationBuilder app, IHostingEnvironment env)  
  2.     {  
  3.       if (env.IsDevelopment())  
  4.       {  
  5.         app.UseDeveloperExceptionPage();  
  6.       }  
  7.   
  8.       app.UseMvc();  
  9.       app.UseMvc(routes =>  
  10.       {  
  11.         routes.MapRoute(  
  12.                   name: "default",  
  13.                   template: "{controller=Home}/{action=Index}/{id?}");  
  14.   
  15.         routes.MapSpaFallbackRoute(  
  16.                   name: "spa-fallback",  
  17.                   defaults: new { controller = "Home", action = "Index" });  
  18.       });  
  19.     }  
Go to launchsettings.json file under Properties directory like below screen capture.

ASP.NET Core

Update "launchUrl": "api/values", value to "launchUrl": "home",
  1. profiles": {  
  2.     "IIS Express": {  
  3.       "commandName""IISExpress",  
  4.       "launchBrowser"true,  
  5.       "launchUrl""api/values",  
  6.       "environmentVariables": {  
  7.         "ASPNETCORE_ENVIRONMENT""Development"  
  8.       }  
Here is the updated launchsettings.json file
  1. {  
  2.   "iisSettings": {  
  3.     "windowsAuthentication"false,  
  4.     "anonymousAuthentication"true,  
  5.     "iisExpress": {  
  6.       "applicationUrl""http://localhost:60769/",  
  7.       "sslPort": 0  
  8.     }  
  9.   },  
  10.   "profiles": {  
  11.     "IIS Express": {  
  12.       "commandName""IISExpress",  
  13.       "launchBrowser"true,  
  14.       "launchUrl""api/values",  
  15.       "environmentVariables": {  
  16.         "ASPNETCORE_ENVIRONMENT""Development"  
  17.       }  
  18.     },  
  19.     "EmployeeJquery.Ui": {  
  20.       "commandName""Project",  
  21.       "launchBrowser"true,  
  22.       "launchUrl""api/values",  
  23.       "environmentVariables": {  
  24.         "ASPNETCORE_ENVIRONMENT""Development"  
  25.       },  
  26.       "applicationUrl""http://localhost:60770/"  
  27.     }  
  28.   }  
  29. }  
Compile and run

ASP.NET Core

Create updateable HTML table and code jQuery AJAX Http Calls

Update the Index.cshtml with below content.-Here is the final result of responsive web design result.

  1. <html>  
  2. <head>  
  3.   <title>SmartIT Employee Manager</title>  
  4.   
  5.   <script src="https://code.jquery.com/jquery-3.2.1.min.js"  
  6.           integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="  
  7.           crossorigin="anonymous"></script>  
  8.   
  9.   <script>  
  10.   
  11.     $(document).ready(function () {  
  12.       getEmployeeList();  
  13.     });  
  14.   
  15.     var Employee = {  
  16.       id: 0,  
  17.       name: "",  
  18.       gender: "",  
  19.       salary: ""  
  20.     }  
  21.   
  22.     // Get all Employees to display  
  23.     function getEmployeeList() {  
  24.       // Call Web API to get a list of Employees  
  25.       $.ajax({  
  26.         url: '/api/GetEmployees/',  
  27.         type: 'GET',  
  28.         dataType: 'json',  
  29.         success: function (employees) {  
  30.           employeeListSuccess(employees);  
  31.         },  
  32.         error: function (request, message, error) {  
  33.           handleException(request, message, error);  
  34.         }  
  35.       });  
  36.     }  
  37.   
  38.     // Display all Employees returned from Web API call  
  39.     function employeeListSuccess(employees) {  
  40.       // Iterate over the collection of data  
  41.       $("#employeeTable tbody").remove();  
  42.       $.each(employees, function (index, employee) {  
  43.         // Add a row to the employee table  
  44.         employeeAddRow(employee);  
  45.       });  
  46.     }  
  47.   
  48.     // Add employee row to <table>  
  49.     function employeeAddRow(employee) {  
  50.       // First check if a <tbody> tag exists, add one if not  
  51.       if ($("#employeeTable tbody").length == 0) {  
  52.         $("#employeeTable").append("<tbody></tbody>");  
  53.       }  
  54.   
  55.       // Append row to <table>  
  56.       $("#employeeTable tbody").append(  
  57.         employeeBuildTableRow(employee));  
  58.     }  
  59.   
  60.     // Build a <tr> for a row of table data  
  61.     function employeeBuildTableRow(employee) {  
  62.       var newRow = "<tr>" +  
  63.         "<td>" + employee.id + "</td>" +  
  64.         "<td><input   class='input-name' type='text' value='" + employee.name + "'/></td>" +  
  65.         "<td><input  class='input-gender'  type='text' value='" + employee.gender + "'/></td>" +  
  66.         "<td><input  class='input-salary' type='text' value='" + employee.salary + "'/></td>" +  
  67.         "<td>" +  
  68.         "<button type='button' " +  
  69.         "onclick='employeeUpdate(this);' " +  
  70.         "class='btn btn-default' " +  
  71.         "data-id='" + employee.id + "' " +  
  72.         "data-name='" + employee.name + "' " +  
  73.         "data-gender='" + employee.gender + "' " +  
  74.         "data-salary='" + employee.salary + "' " +  
  75.         ">" +  
  76.         "<span class='glyphicon glyphicon-edit' /> Update" +  
  77.         "</button> " +  
  78.         " <button type='button' " +  
  79.         "onclick='employeeDelete(this);'" +  
  80.         "class='btn btn-default' " +  
  81.         "data-id='" + employee.id + "'>" +  
  82.         "<span class='glyphicon glyphicon-remove' />Delete" +  
  83.         "</button>" +  
  84.         "</td>" +  
  85.         "</tr>";  
  86.   
  87.       return newRow;  
  88.     }  
  89.   
  90.     function onAddEmployee(item) {  
  91.       var options = {};  
  92.       options.url = "/api/AddEmployee";  
  93.       options.type = "POST";  
  94.       var obj = Employee;  
  95.       obj.name = $("#name").val();  
  96.       obj.gender = $("#gender").val();  
  97.       obj.salary = $("#salary").val();  
  98.       console.dir(obj);  
  99.       options.data = JSON.stringify(obj);  
  100.       options.contentType = "application/json";  
  101.       options.dataType = "html";  
  102.   
  103.       options.success = function (msg) {  
  104.         getEmployeeList();  
  105.         $("#msg").html(msg);  
  106.       },  
  107.         options.error = function () {  
  108.           $("#msg").html("Error while calling the Web API!");  
  109.         };  
  110.       $.ajax(options);  
  111.     }  
  112.   
  113.     function employeeUpdate(item) {  
  114.       var id = $(item).data("id");  
  115.       var options = {};  
  116.       options.url = "/api/UpdateEmployee/"  
  117.       options.type = "PUT";  
  118.   
  119.       var obj = Employee;  
  120.       obj.id = $(item).data("id");  
  121.       obj.name = $(".input-name", $(item).parent().parent()).val();  
  122.       obj.gender = $(".input-gender", $(item).parent().parent()).val();  
  123.       obj.salary = $(".input-salary", $(item).parent().parent()).val();  
  124.       console.dir(obj);  
  125.       options.data = JSON.stringify(obj);  
  126.       options.contentType = "application/json";  
  127.       options.dataType = "html";  
  128.       options.success = function (msg) {  
  129.         $("#msg").html(msg);  
  130.       };  
  131.       options.error = function () {  
  132.         $("#msg").html("Error while calling the Web API!");  
  133.       };  
  134.       $.ajax(options);  
  135.     }  
  136.   
  137.     function employeeDelete(item) {  
  138.       var id = $(item).data("id");  
  139.       var options = {};  
  140.       options.url = "/api/DeleteEmployee/"  
  141.         + id;  
  142.       options.type = "DELETE";  
  143.       options.dataType = "html";  
  144.       options.success = function (msg) {  
  145.         console.log('msg= ' + msg);  
  146.         $("#msg").html(msg);  
  147.         getEmployeeList();  
  148.       };  
  149.       options.error = function () {  
  150.         $("#msg").html("Error while calling the Web API!");  
  151.       };  
  152.       $.ajax(options);  
  153.     }  
  154.   
  155.     // Handle exceptions from AJAX calls  
  156.     function handleException(request, message, error) {  
  157.       var msg = "";  
  158.       msg += "Code: " + request.status + "\n";  
  159.       msg += "Text: " + request.statusText + "\n";  
  160.       if (request.responseJSON != null) {  
  161.         msg += "Message" + request.responseJSON.Message + "\n";  
  162.       }  
  163.   
  164.       alert(msg);  
  165.     }  
  166.   </script>  
  167. </head>  
  168. <body>  
  169.   <h3>Employee Manager</h3>  
  170.   <form>  
  171.     <table id="employeeTable" style="border: 1px solid #999" cellpadding="1">  
  172.       <thead>  
  173.         <tr>  
  174.           <td>Id </td>  
  175.           <td> Name </td>  
  176.           <td> Gender </td>  
  177.           <td> Salary </td>  
  178.           <td> </td>  
  179.         </tr>  
  180.         <tr>  
  181.           <td></td>  
  182.           <td><input id="name" type="text" /></td>  
  183.           <td><input id="gender" type="text" /></td>  
  184.           <td><input id="salary" type="text" /></td>  
  185.           <td><input type="button" id="insert" value="Insert" onclick='onAddEmployee(this)' /></td>  
  186.       </thead>  
  187.     </table>  
  188.     <br />  
  189.     <div id="msg"></div>  
  190.   </form>  
  191.   Copyright 2017 (c) SmartIT. All rights reserved. By John Kocer  
  192. </body>  
  193. </html>  

ASP.NET Core

Summary

In this article, we will learned,

  • How to consume Employee in-memory database using EmployeeRepository.
  • How to create ASP.NET Core custom API controller with CRUD operations.
  • Getting List of Objects
  • Create a new insert item
  • Update an Item
  • Delete an Item
  • Write HttpPost Create API method.
  • Write HttpPut Update API method.
  • Write HttpPost Delete API method.
  • Route table
  • Set start controller Route to Home Index method.
  • jQuery/HTML pass table row value to a JavaScript function
  • jQuery Ajax HttpGet
  • jQuery Ajax HttpPut
  • jQuery Ajax HttpPost
  • Editable HTML table
  • Responsive Web Design

Lab Exercise

A lab exercise for you to demonstrate what have you learned from this training material to create your own Todo JQuery CRUD Responsive Design SPA application. The TodoRepository included in this training material.

You can follow above steps to create your own To-do CRUD ASP.NET MVC jQuery application.

  1. TodoRepository _todoRepository = new TodoRepository();    
  2. var todoList = _todoRepository.GetAll();    
  3. todoList.CDump("_todoRepository.GetAll()");    
  4. var findById = _todoRepository.FindById(2);    
  5. findById.CDump("_todoRepository.FindById(2)");    
  6. var newTodo = _todoRepository.Add(new Todo { Name = "Call a friend" });    
  7. _todoRepository.GetAll().CDump("Check if Call a friend todo added?");    
  8. newTodo.Name = newTodo.Name + " Updated";    
  9. _todoRepository.Update(newTodo);    
  10. _todoRepository.GetAll().CDump("Check if Call a friend todo updated with Updated?");    
  11. _todoRepository.Delete(_todoRepository.FindById(1));    
  12. _todoRepository.GetAll().CDump("Check if Id=1 todo is Deleted?");    

Download source code from GitHub.

Thank you for reading this article. You may be interested below Training articles to.

Up Next
    Ebook Download
    View all
    Learn
    View all