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.
Add a new ASP.NET Core Web Application project and name it as EmployeeJquery.Ui.
On the next screen, select Web API project template.
Compile and run the application and we’ll see the home page.
We want to create the below single page application with CRUD operations - Add, Update, and Remove functionality with in-memory EmployeeRepository Database.
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.
Create EmployeeController
In the Controllers directory, add a new Web API controller Class and Add.
EmployeeController will be created.
- namespace EmployeeJquery.Ui.Controllers
- {
- [Route("api/[controller]")]
- public class EmployeeController : Controller
- {
-
- [HttpGet]
- public IEnumerable<string> Get()
- {
- return new string[] { "value1", "value2" };
- }
-
-
- [HttpGet("{id}")]
- public string Get(int id)
- {
- return "value";
- }
-
-
- [HttpPost]
- public void Post([FromBody]string value)
- {
- }
-
-
- [HttpPut("{id}")]
- public void Put(int id, [FromBody]string value)
- {
- }
-
-
- [HttpDelete("{id}")]
- public void Delete(int id)
- {
- }
- }
- }
Replace the EmployeeController code with the below code which has all the APIs for CRUD operation.
- using System.Collections.Generic;
- using Microsoft.AspNetCore.Mvc;
- using SmartIT.Employee.MockDB;
-
- namespace EmployeeJquery.Ui.Controllers
- {
- [Produces("application/json")]
- [Route("api/Employee")]
- public class EmployeeController : Controller
- {
-
- private EmployeeRepository db = new EmployeeRepository();
-
- [Route("~/api/GetEmployees")]
- [HttpGet]
- public ICollection<Employee> GetEmployees()
- {
- return db.GetAll();
- }
-
- [HttpGet("{id}")]
- public Employee Get(int id)
- {
- return db.FindbyId(id);
- }
-
- [Route("~/api/AddEmployee")]
- [HttpPost]
- public IActionResult AddEmployee([FromBody]Employee obj)
- {
- db.Add(obj);
- return new ObjectResult("Employee added successfully!");
- }
-
- [Route("~/api/UpdateEmployee")]
- [HttpPut]
- public IActionResult UpdateEmployee([FromBody]Employee obj)
- {
- db.Update(obj);
- return new ObjectResult( "Employee modified successfully!");
- }
-
- [Route("~/api/DeleteEmployee/{id}")]
- [HttpDelete]
- public IActionResult Delete(int id)
- {
- db.Delete(db.FindbyId(id));
- return new ObjectResult("Employee deleted successfully!");
- }
- }
- }
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.
Creating a Client by Using jQuery Ajax
Add an MVC Controller Class in Controller directory.
A HomeController will be created ike below.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- using Microsoft.AspNetCore.Mvc;
-
-
-
- namespace EmployeeJquery.Ui.Controllers
- {
- public class HomeController : Controller
- {
-
- public IActionResult Index()
- {
- return View();
- }
- }
- }
Add 2 directory under Controller Views and Home like below.
Add an MVC View Page on the Home directory like below.
An empty Index.cshtml will be created like below.
- @*
- For more information on enabling MVC for empty projects, visit https:
- *@
- @{
- }
-
- @*
- For more information on enabling MVC for empty projects, visit https:
- *@
- @{
- }
- 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.
- public void Configure(IApplicationBuilder app, IHostingEnvironment env)
- {
- if (env.IsDevelopment())
- {
- app.UseDeveloperExceptionPage();
- }
-
- app.UseMvc();
- app.UseMvc(routes =>
- {
- routes.MapRoute(
- name: "default",
- template: "{controller=Home}/{action=Index}/{id?}");
-
- routes.MapSpaFallbackRoute(
- name: "spa-fallback",
- defaults: new { controller = "Home", action = "Index" });
- });
- }
Go to launchsettings.json file under Properties directory like below screen capture.
Update "launchUrl": "api/values", value to "launchUrl": "home",
- profiles": {
- "IIS Express": {
- "commandName": "IISExpress",
- "launchBrowser": true,
- "launchUrl": "api/values",
- "environmentVariables": {
- "ASPNETCORE_ENVIRONMENT": "Development"
- }
Here is the updated launchsettings.json file
- {
- "iisSettings": {
- "windowsAuthentication": false,
- "anonymousAuthentication": true,
- "iisExpress": {
- "applicationUrl": "http://localhost:60769/",
- "sslPort": 0
- }
- },
- "profiles": {
- "IIS Express": {
- "commandName": "IISExpress",
- "launchBrowser": true,
- "launchUrl": "api/values",
- "environmentVariables": {
- "ASPNETCORE_ENVIRONMENT": "Development"
- }
- },
- "EmployeeJquery.Ui": {
- "commandName": "Project",
- "launchBrowser": true,
- "launchUrl": "api/values",
- "environmentVariables": {
- "ASPNETCORE_ENVIRONMENT": "Development"
- },
- "applicationUrl": "http://localhost:60770/"
- }
- }
- }
Compile and run
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.
- <html>
- <head>
- <title>SmartIT Employee Manager</title>
-
- <script src="https://code.jquery.com/jquery-3.2.1.min.js"
- integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
- crossorigin="anonymous"></script>
-
- <script>
-
- $(document).ready(function () {
- getEmployeeList();
- });
-
- var Employee = {
- id: 0,
- name: "",
- gender: "",
- salary: ""
- }
-
-
- function getEmployeeList() {
-
- $.ajax({
- url: '/api/GetEmployees/',
- type: 'GET',
- dataType: 'json',
- success: function (employees) {
- employeeListSuccess(employees);
- },
- error: function (request, message, error) {
- handleException(request, message, error);
- }
- });
- }
-
-
- function employeeListSuccess(employees) {
-
- $("#employeeTable tbody").remove();
- $.each(employees, function (index, employee) {
-
- employeeAddRow(employee);
- });
- }
-
-
- function employeeAddRow(employee) {
-
- if ($("#employeeTable tbody").length == 0) {
- $("#employeeTable").append("<tbody></tbody>");
- }
-
-
- $("#employeeTable tbody").append(
- employeeBuildTableRow(employee));
- }
-
-
- function employeeBuildTableRow(employee) {
- var newRow = "<tr>" +
- "<td>" + employee.id + "</td>" +
- "<td><input class='input-name' type='text' value='" + employee.name + "'/></td>" +
- "<td><input class='input-gender' type='text' value='" + employee.gender + "'/></td>" +
- "<td><input class='input-salary' type='text' value='" + employee.salary + "'/></td>" +
- "<td>" +
- "<button type='button' " +
- "onclick='employeeUpdate(this);' " +
- "class='btn btn-default' " +
- "data-id='" + employee.id + "' " +
- "data-name='" + employee.name + "' " +
- "data-gender='" + employee.gender + "' " +
- "data-salary='" + employee.salary + "' " +
- ">" +
- "<span class='glyphicon glyphicon-edit' /> Update" +
- "</button> " +
- " <button type='button' " +
- "onclick='employeeDelete(this);'" +
- "class='btn btn-default' " +
- "data-id='" + employee.id + "'>" +
- "<span class='glyphicon glyphicon-remove' />Delete" +
- "</button>" +
- "</td>" +
- "</tr>";
-
- return newRow;
- }
-
- function onAddEmployee(item) {
- var options = {};
- options.url = "/api/AddEmployee";
- options.type = "POST";
- var obj = Employee;
- obj.name = $("#name").val();
- obj.gender = $("#gender").val();
- obj.salary = $("#salary").val();
- console.dir(obj);
- options.data = JSON.stringify(obj);
- options.contentType = "application/json";
- options.dataType = "html";
-
- options.success = function (msg) {
- getEmployeeList();
- $("#msg").html(msg);
- },
- options.error = function () {
- $("#msg").html("Error while calling the Web API!");
- };
- $.ajax(options);
- }
-
- function employeeUpdate(item) {
- var id = $(item).data("id");
- var options = {};
- options.url = "/api/UpdateEmployee/"
- options.type = "PUT";
-
- var obj = Employee;
- obj.id = $(item).data("id");
- obj.name = $(".input-name", $(item).parent().parent()).val();
- obj.gender = $(".input-gender", $(item).parent().parent()).val();
- obj.salary = $(".input-salary", $(item).parent().parent()).val();
- console.dir(obj);
- options.data = JSON.stringify(obj);
- options.contentType = "application/json";
- options.dataType = "html";
- options.success = function (msg) {
- $("#msg").html(msg);
- };
- options.error = function () {
- $("#msg").html("Error while calling the Web API!");
- };
- $.ajax(options);
- }
-
- function employeeDelete(item) {
- var id = $(item).data("id");
- var options = {};
- options.url = "/api/DeleteEmployee/"
- + id;
- options.type = "DELETE";
- options.dataType = "html";
- options.success = function (msg) {
- console.log('msg= ' + msg);
- $("#msg").html(msg);
- getEmployeeList();
- };
- options.error = function () {
- $("#msg").html("Error while calling the Web API!");
- };
- $.ajax(options);
- }
-
-
- function handleException(request, message, error) {
- var msg = "";
- msg += "Code: " + request.status + "\n";
- msg += "Text: " + request.statusText + "\n";
- if (request.responseJSON != null) {
- msg += "Message" + request.responseJSON.Message + "\n";
- }
-
- alert(msg);
- }
- </script>
- </head>
- <body>
- <h3>Employee Manager</h3>
- <form>
- <table id="employeeTable" style="border: 1px solid #999" cellpadding="1">
- <thead>
- <tr>
- <td>Id </td>
- <td> Name </td>
- <td> Gender </td>
- <td> Salary </td>
- <td> </td>
- </tr>
- <tr>
- <td></td>
- <td><input id="name" type="text" /></td>
- <td><input id="gender" type="text" /></td>
- <td><input id="salary" type="text" /></td>
- <td><input type="button" id="insert" value="Insert" onclick='onAddEmployee(this)' /></td>
- </thead>
- </table>
- <br />
- <div id="msg"></div>
- </form>
- Copyright 2017 (c) SmartIT. All rights reserved. By John Kocer
- </body>
- </html>
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.
- TodoRepository _todoRepository = new TodoRepository();
- var todoList = _todoRepository.GetAll();
- todoList.CDump("_todoRepository.GetAll()");
- var findById = _todoRepository.FindById(2);
- findById.CDump("_todoRepository.FindById(2)");
- var newTodo = _todoRepository.Add(new Todo { Name = "Call a friend" });
- _todoRepository.GetAll().CDump("Check if Call a friend todo added?");
- newTodo.Name = newTodo.Name + " Updated";
- _todoRepository.Update(newTodo);
- _todoRepository.GetAll().CDump("Check if Call a friend todo updated with Updated?");
- _todoRepository.Delete(_todoRepository.FindById(1));
- _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.