Hands-On ASP.NET Core 3.1 : Learn MVC, Razor Pages, Web API, Entity Framework Core, and Blazor. Private online coaching for software developers. Click here to know more.

TypeScript class for UI callback functions and the Web API

In the previous part of this article and video series you developed a  TypeScript class that invokes an ASP.NET Core Web API using XMLHttpRequest object. Recollect from the previous part that the EmployeeApiClient class expects a few callback functions. These callback functions receive the response returned by the Employees Web API and display it on to the web page. In this part you will create another TypeScript class that houses those callback functions. You will also create the Employees Web API that performs the CRUD operations. Finally, you will test the functioning of both the TypeScript classes (and the Employees Web API) by calling their methods from a web page.

Begin by opening the same project that you created previously and go to the Classes.ts file.

Inside, add a class named EmployeeAppUi and implement the IEmployeeAppUi interface in it. The following code shows the skeleton of this class:

class EmployeeAppUi implements IEmployeeAppUi {

    getCallback(data: IEmployee[]): void {
    }

    getByIDCallback(data: IEmployee): void {
    }

    postCallback(msg: string): void {
    }

    putCallback(msg: string): void {
    }

    deleteCallback(msg: string): void {
    }
}

The EmployeeAppUi class implements five functions - getCallback(), getByIDCallback(), postCallback(), putCallback(), and deleteCallback(). These callback functions are discussed below.

The getCallback() function is invoked by EmployeeApiClient class upon receiving a list of employees from the Employees Web API. This function is shown below:

getCallback(data: IEmployee[]): void {
    let table: string = "<table>";

    for (let i in data) {
        table += "<tr>";
        table += "<td>" + 
data[i].employeeID + "</td>";
        table += "<td>" + 
data[i].firstName + "</td>";
        table += "<td>" + 
data[i].lastName + "</td>";
        table += "<td>" + 
data[i].title + "</td>";
        table += "</tr>";
    }
    table += "</table>";
    document.getElementById("msg")
.innerHTML = table;
}

The getCallback() function receives an arrat of IEmployee objects as its data parameter. Inside, it forms a table markup by iterating through all the employee objects and grabbing the values of employeeID, firstName, lastName, and title properties. The <table> markup is then assigned to the innerHTML property of the msg <div> element. You will create the web page with the msg <div> later in this part.

The getByIDCallback() is similar to getCallback() except that it receives a single employee object and displays just that on the page.

getByIDCallback(data: IEmployee): void {
    let table: string = "<table>";
    table += "<tr>";
    table += "<td>" + 
data.employeeID + "</td>";
    table += "<td>" + 
data.firstName + "</td>";
    table += "<td>" + 
data.lastName + "</td>";
    table += "<td>" + 
data.title + "</td>";
    table += "</tr>";
    table += "</table>";
    document.getElementById("msg")
.innerHTML = table;
}

The postCallback(), putCallback(), and deleteCallback() functions simply render the success message returned from the Web API on the page:

postCallback(msg: string): void {
    document.getElementById("msg")
.innerHTML = "<h1>" + msg + "</h1>";
}

putCallback(msg: string): void {
    document.getElementById("msg")
.innerHTML = "<h1>" + msg + "</h1>";
}

deleteCallback(msg: string): void {
    document.getElementById("msg")
.innerHTML = "<h1>" + msg + "</h1>";
}

This completes the EmployeeAppUi class. Now, let's create the Employees Web API.

The Employees Web API performs CRUD operations on the Employees table of the Northwind database. So, you need EF Core model. The Employee entity class required by the model is shown below:

[Table("Employees")]
public class Employee
{
    public int EmployeeID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Title { get; set; }
}

And the DbContext class looks like this:

public class AppDbContext:DbContext
{
    public AppDbContext(DbContextOptions
<AppDbContext> options) : base(options)
    {
    }

    public DbSet<Employee> Employees { get; set; }
}

Then add EmployeesController Web API controller class to the Controllers folder. And add the Get(), Post(), Put(), and Delete() actions as shown below:

[Route("api/[controller]")]
public class EmployeesController : Controller
{

    private readonly AppDbContext db;

    public EmployeesController(AppDbContext db)
    {
        this.db = db;
    }

    [HttpGet]
    public List<Employee> Get()
    {
        return db.Employees.ToList();
    }

    [HttpGet("{id}")]
    public Employee Get(int id)
    {
        return db.Employees.Find(id);
    }

    [HttpPost]
    public string Post([FromBody]Employee emp)
    {
        db.Employees.Add(emp);
        db.SaveChanges();
        return "Success!";
    }

    [HttpPut("{id}")]
    public string Put(int id, 
[FromBody]Employee emp)
    {
        db.Employees.Update(emp);
        db.SaveChanges();
        return "Success!";
    }

    [HttpDelete("{id}")]
    public string Delete(int id)
    {
        db.Employees.Remove
(db.Employees.Find(id));
        db.SaveChanges();
        return "Success!";
    }
}

Since the EmployeesApi controller is quite straightforward I am not going to discuss it in any more details.

Now we have EmployeeApiClient and EmployeeAppUi classes, and Employees Web API ready, let's create a sample web page that makes use of what we created so far.

Add a new HTML page named Classes.html and write the following in it:

<body>
  <button onclick="OnGetClick()">Get</button>
  <button onclick="OnGetByIDClick()">Get By ID</button>
  <button onclick="OnPostClick()">Post</button>
  <button onclick="OnPutClick()">Put</button>
  <button onclick="OnDeleteClick()">Delete</button>
  <br /><br />
  <div id="msg"></div>
  <script src="/TypeScript/Output/Classes.js"></script>
</body>

As you can see, the web page consists of five buttons, the msg <div>, and the <script> reference to Classes.js file.

The click event handler functions such as OnGetClick() and OnPostClick() are added to the Classes.ts file and are shown below:

let client = new EmployeeApiClient
    ("http://localhost:49589/api/employees");

let ui = new EmployeeAppUi();

function OnGetClick() {
    client.get(ui.getCallback);
}


function OnGetByIDClick() {
    client.getByID(1,ui.getByIDCallback);
}

function OnPostClick() {
    let data: IEmployee = {
        firstName: "First Name 1",
        lastName: "Last Name 1",
        title: "Sales Executive"
    };
    client.post(data, ui.postCallback);
}

function OnPutClick() {
    let data: IEmployee = {
        employeeID: 1154,
        firstName: "Tom123",
        lastName: "Jerry123",
        title: "Sales Executive"
    };
    client.put(data, ui.postCallback);
}

function OnDeleteClick() {
    client.delete(1153, ui.postCallback);
}

This code begins by creating an object of EmployeeApiClient and EmployeeAppUi classes created earlier. We pass the URL of the Web API end-point to the EmployeeApiClient constructor. Make sure to change this URL as per your development setup.

Then a series of click event handlers invoke the get(), getByID(), post(), put(), and delete() methods of the EmployeeApiClient object. Inside, OnPutClick() and OnDeleteClick() make sure to change the EmployeeID as per your database.

You can now run the Classes.html page in the browser and test if it works as expected. Here is a sample run of the page:

That's it for now! Keep coding!!


Bipin Joshi is an independent software consultant, trainer, author, yoga mentor, and meditation teacher. He has been programming, meditating, and teaching for 24+ years. He conducts instructor-led online training courses in ASP.NET family of technologies for individuals and small groups. He is a published author and has authored or co-authored books for Apress and Wrox press. Having embraced the Yoga way of life he also teaches Ajapa Yoga to interested individuals. To know more about him click here.

Get connected : Facebook  Twitter  LinkedIn  YouTube

Posted On : 27 April 2020


Tags : ASP.NET ASP.NET Core MVC .NET Framework C# Visual Studio


Subscribe to our newsletter

Get monthly email updates about new articles, tutorials, code samples, and how-tos getting added to our knowledge base.

  

Receive Weekly Updates