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

Employee Manager

Introduction

In this session, we will learn

  • How to consume the Employee in-memory database using EmployeeRepository.
  • How to create an ASP.NET Core custom API controller with CRUD operations.
  • Getting a 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 the 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.

New Project

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.

Localhost Value1,2

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

Employee Added Succesfully

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 Todo repository

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 employee controller

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

Add New Item

EmployeeController will be created.

namespace EmployeeJquery.Ui.Controllers
{
    [Route("api/[controller]")]
    public class EmployeeController : Controller
    {
        // GET: api/values
        [HttpGet]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/values/5
        [HttpGet("{id}")]
        public string Get(int id)
        {
            return "value";
        }

        // POST api/values
        [HttpPost]
        public void Post([FromBody]string value)
        {
        }

        // PUT api/values/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/values/5
        [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.

Localhost Id

Creating a client by using jQuery Ajax

Add an MVC Controller Class in the Controller directory.

Add New Item MVC

A HomeController will be created ike below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace EmployeeJquery.Ui.Controllers
{
    public class HomeController : Controller
    {
        // GET: /<controller>/
        public IActionResult Index()
        {
            return View();
        }
    }
}

Add 2 directories under Controller Views and Home like below.

ASP.NET Core

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

Add New Item MVC View Page

An empty Index.CSS HTML will be created like below.

@*   
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860   
*@   
@{
}

SmartIT by JohnKocer

Update API routing to go Home page

Add a route into Startup.cs page’s Configure method for the HomeController is 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 the launchsettings.json file under Properties directory like below screen capture below.

ASP.NET Core

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

Smart IT

Create updateable HTML table and code jQuery AJAX Http Calls

Update the Index. CSS HTML with the below content is the final result of the 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: ""
        }

        // Get all Employees to display
        function getEmployeeList() {
            // Call Web API to get a list of Employees
            $.ajax({
                url: '/api/GetEmployees/',
                type: 'GET',
                dataType: 'json',
                success: function (employees) {
                    employeeListSuccess(employees);
                },
                error: function (request, message, error) {
                    handleException(request, message, error);
                }
            });
        }

        // Display all Employees returned from Web API call
        function employeeListSuccess(employees) {
            // Iterate over the collection of data
            $("#employeeTable tbody").remove();
            $.each(employees, function (index, employee) {
                // Add a row to the employee table
                employeeAddRow(employee);
            });
        }

        // Add employee row to <table>
        function employeeAddRow(employee) {
            // First check if a <tbody> tag exists, add one if not
            if ($("#employeeTable tbody").length == 0) {
                $("#employeeTable").append("<tbody></tbody>");
            }

            // Append row to <table>
            $("#employeeTable tbody").append(
                employeeBuildTableRow(employee));
        }

        // Build a <tr> for a row of table data
        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);
        }

        // Handle exceptions from AJAX calls
        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>
        </tr>
        </thead>
    </table>
    <br/>
    <div id="msg"></div>
</form>
Copyright 2017 (c) SmartIT. All rights reserved. By John Kocer
</body>
</html>

Employee Added Succesfully

Summary

In this article, we will learn

  • How to consume the Employee in-memory database using EmployeeRepository.
  • How to create the 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.

Resources