In this article I will show how to create JavaScript Frontend for Web API CRUD operations using Bootstrap and some simple javascript code as shown in the below image.
Some time back I had written BookStore Web API in ASP.Net Core that perform simple CRUD operations using Entity Framework Core and uses SQL Server Express edition as back-end for data storage and retrieval.
Check out my article on creating this BookStore Web API for which I will be sharing how to create javascript frontend in this article.
Prerequisites
- In order to run the BookStore Web API you will need .Net Core SDK that includes .Net CLI tools, .Net Core Runtime. So download and install the latest version of .Net Core SDK available from this link.
- We will also need code editor, I will recommend VS Code but if you already have any other code editor that you are using to write C# code then stick with that otherwise download and install VS Code from this link. After installing SDK and VS Code, open the command prompt and run following command to check if SDK installed properly.
$ dotnet –version
You must get the latest version number as a result. For me its 3.1.
- And last, we need to have SQL Server installed on the machine. In case you already have Visual Studio 2015 or later installed then SQL Server Express edition will already be installed along with the Visual Studio. Otherwise download and install latest SQL Server Express edition free from this link.
After done with the environment setup we are ready to create JavaScript Frontend for our BookStore Web API CRUD operations.
Get Started…
Here we need few things before we actually start writing some html/javascript code to develop the frontend.
- First, we need BookStore Web API code on top of which we will develop frontend.
- Second, we need to create scaffolding to contain frontend code.
- Finally, get some readymade html/css/javascript code for frontend by using Bootstrap template for Data table and Modal Forms. So let’s get started…
Get Source code
- Get the source code of BookStore Web API from my GitHub repository link by downloading the ZIP file from “Clone and download” button and unzip it in the folder on your machine.
- Follow the instructions in the README.md file to setup the code for further development.
- Open the command window in the folder where you unzipped the source code and start VS Code editor by running following command in the command window.
$ vscode .
- Before we begin developing frontend we need to make few minor changes in our Web API code application in order to make it work like a website.
- First, we need to force the application to open the index.html instead of Web API so open the Properties\launchSettings.json file and remove the launchUrl property.
- Second, we want to make sure our application serves static files (html/css/javascript) to the web client and also serve the default file (in our case index.html) when site loads into browser. So add following code in the Configure method of Startup.cs.
app.UseDefaultFiles();
app.UseStaticFiles();
Create JavaScript Frontend
- We will start with creating scaffolding for our frontend. So create following file/folder structure that will contain all our frontend code.
- Create wwwroot folder at the root folder of the application.
- Create index.html file in the wwwroot folder.
- Create js folder in the wwwroot folder.
- Create site.js folder in the js folder.
- Create css folder in the wwwroot folder.
- Create site.css folder in the css folder.
- We will not write all the html/CSS code for our frontend instead we will get some readymade html/CSS code for showing Data Table with Modal Form for CRUD operations by using Bootstrap template for Data Table with Modal Form. So to get the Bootstrap template, open this link and click on view code and copy the source code in the index.html file.
- Remove all “checkbox” elements and pagination related code from the index.html since we just want to focus on CRUD operations related UI right now.
- Cut out all the CSS code between <style type="text/css"> tag from the index.html file and paste it in the site.css file. And add following code in the <head> section of index.html.
<link rel="stylesheet" href="css/site.css" />
Although we could keep the CSS code in the index.html file but as a best practice we should always keep all style related code in the separate folder.
Code change for Web API CRUD Operations
Now we will make html/javascript code changes to integrate Web API CRUD operations like getting/showing the data, creating, updating and deleting the data resource through frontend.
Code change for getting data and showing it on the data table in UI.
- Remove all code between <table class="table table-striped table-hover w-auto"> tag and replace it with following code in the index.html file.
<thead>
<tr>
<th>Title</th>
<th>Author</th>
<th>Publisher</th>
<th>Genre</th>
<th>Price</th>
<th>Actions</th>
</tr>
</thead>
<tbody id="books"></tbody>
- Add following code under <div class="clearfix"> to show the number of records.
<div id="counter" class="hint-text"></div>
- Also add following javascript tag just above the </body> tag in the index.html file.
<script src="js/site.js" asp-append-version="true"></script>
<script type="text/javascript">
getBookItems();
</script>
- Add following javascript code in the site.js file that will make the Web API GET call to fetch the data from database and display it on the UI.
const uri = "api/BookItems";
let books = [];
function getBookItems() {
fetch(uri)
.then(response => response.json())
.then(data => _displayItems(data))
.catch(error => console.error("Unable to get books.", error));
}
function displayDeleteForm(id) {
const item = books.find(item => item.id === id);
document.getElementById("delete-id").value = item.id;
}
function displayEditForm(id) {
const item = books.find(item => item.id === id);
document.getElementById("edit-id").value = item.id;
document.getElementById("edit-title").value = item.title;
document.getElementById("edit-author").value = item.author;
document.getElementById("edit-publisher").value = item.publisher;
document.getElementById("edit-genre").value = item.genre;
document.getElementById("edit-price").value = item.price;
}
function _displayCount(itemCount) {
const name = itemCount === 1 ? "entry" : "entries";
document.getElementById(
"counter"
).innerHTML = `Showing <b>${itemCount}</b> ${name}`;
}
function _displayItems(data) {
const tBody = document.getElementById("books");
tBody.innerHTML = "";
_displayCount(data.length);
const button = document.createElement("button");
data.forEach(item => {
let editButton = document.createElement("a");
editButton.href = "#editBookModal";
editButton.className = "edit";
editButton.setAttribute("onclick", `displayEditForm(${item.id})`);
editButton.setAttribute("data-toggle", "modal");
editButton.innerHTML =
"<i class='material-icons' data-toggle='tooltip' title='Edit'></i>";
let deleteButton = document.createElement("a");
deleteButton.href = "#deleteBookModal";
deleteButton.className = "delete";
deleteButton.setAttribute("onclick", `displayDeleteForm(${item.id})`);
deleteButton.setAttribute("data-toggle", "modal");
deleteButton.innerHTML =
"<i class='material-icons' data-toggle='tooltip' title='Delete'></i>";
let tr = tBody.insertRow();
let td1 = tr.insertCell(0);
let textTitle = document.createTextNode(item.title);
td1.appendChild(textTitle);
let td2 = tr.insertCell(1);
let textAuthor = document.createTextNode(item.author);
td2.appendChild(textAuthor);
let td3 = tr.insertCell(2);
let textPublisher = document.createTextNode(item.publisher);
td3.appendChild(textPublisher);
let td4 = tr.insertCell(3);
let textGenre = document.createTextNode(item.genre);
td4.appendChild(textGenre);
let td5 = tr.insertCell(4);
let textPrice = document.createTextNode(item.price);
td5.appendChild(textPrice);
let td6 = tr.insertCell(5);
td6.appendChild(editButton);
td6.appendChild(deleteButton);
});
books = data;
}
Code change for Add Book Model form and creating/saving the data.
- Replace code in the <div class="col-sm-6"> tag with the following code to show “Add New Book” modal form.
<a
href="#addBookModal"
class="btn btn-success"
data-toggle="modal"
><i class="material-icons"></i>
<span>Add New Book</span></a
>
Replace the top level div id with “addBookModal” under the <!– Add Modal HTML –> section that contains html code for Add Modal Form.
Replace <form> tag with following code.
<form action="javascript:void(0);" method="POST" onsubmit="addBookItem()">
- Also edit the existing <label> to show Title, Author, Publisher, Genre and Price.
- And edit <input> tags with following <input> tags so the end result should look like the form below.
<input type="text" id="add-title" placeholder="Enter Book Title"
class="form-control" required />
<input type="text" id="add-author" placeholder="Enter Book Author"
class="form-control" required />
<input type="text" id="add-publisher" placeholder="Enter Book Publisher"
class="form-control" required />
<input type="text" id="add-genre" placeholder="Enter Book Genre"
class="form-control" required />
<input type="text" id="add-price" placeholder="Enter Book Price"
class="form-control" required />
- Add following javascript code in the site.js that will make Web API POST call to save/create the data.
function addBookItem() {
const titleInputText = document.getElementById("add-title");
const auhtorInputText = document.getElementById("add-author");
const publisherInputText = document.getElementById("add-publisher");
const genreInputText = document.getElementById("add-genre");
const priceInputText = document.getElementById("add-price");
const item = {
title: titleInputText.value.trim(),
author: auhtorInputText.value.trim(),
publisher: publisherInputText.value.trim(),
genre: genreInputText.value.trim(),
price: parseInt(priceInputText.value.trim())
};
console.log(JSON.stringify(item));
fetch(uri, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(item)
})
.then(response => response.json())
.then(() => {
getBookItems();
titleInputText.value = "";
auhtorInputText.value = "";
publisherInputText.value = "";
genreInputText.value = "";
priceInputText.value = "";
})
.catch(error => console.error("Unable to add Book.", error));
}
Code change for Edit Book Model form and updating the data.
Under the <!– Edit Modal HTML –> section that contains html code for Edit Modal Form, replace the top level div id with “editBookModal”.
Replace <form> tag with following code.
<form action="javascript:void(0);" onsubmit="updateBookItem()">
- Also edit the existing <label> to show Title, Author, Publisher, Genre and Price.
- And edit <input> tags the same way we did for “Add Book” form with the <input> tags code we used there but make sure the id value of input tags should be prefixed with edit instead of add this time so the end result should look like the form below.
- Add following javascript code in the site.js that will make Web API PUT call to update the data.
function updateBookItem() {
const itemId = document.getElementById("edit-id").value.trim();
const item = {
id: parseInt(itemId, 10),
title: document.getElementById("edit-title").value.trim(),
author: document.getElementById("edit-author").value.trim(),
publisher: document.getElementById("edit-publisher").value.trim(),
genre: document.getElementById("edit-genre").value.trim(),
price: parseInt(document.getElementById("edit-price").value.trim())
};
fetch(`${uri}/${itemId}`, {
method: "PUT",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(item)
})
.then(() => getBookItems())
.catch(error => console.error("Unable to update item.", error));
return false;
}
Code change for Delete Book Model form and deleting the data.
Finally, under the <!– Delete Modal HTML –> section that contains html code for Delete Modal Form, replace the top level div id with “deleteBookModal”.
And replace <form> tag with following code.
<form action="javascript:void(0);" onsubmit="deleteBookItem()">
Also change the text under H4 tag that will appear as form title for all the forms accordingly.
- Add following javascript code in the site.js that will make Web API DELETE call to delete the data.
function deleteBookItem() {
const itemId = document.getElementById("delete-id").value.trim();
fetch(`${uri}/${itemId}`, {
method: "DELETE"
})
.then(() => getBookItems())
.catch(error => console.error("Unable to delete Book.", error));
}
- Finally add following jqury code under <script type="text/javascript"> tag in the index.html file to force the Modal Forms to close when we submit them.
$("#addBookModal").submit(function() {
$("#addBookModal").modal("hide");
});
$("#editBookModal").submit(function() {
$("#editBookModal").modal("hide");
});
$("#deleteBookModal").submit(function() {
$("#deleteBookModal").modal("hide");
});
I have covered all major code changes in this article to implement the CRUD operations however if I missed any cosmetic changes like label text etc. then try to fix them yourself.
OR
You can get the complete source code of what we have developed here from this link of my GitHub repository.
Keep learning and…subscribe to my blog if you liked this article.
Top comments (0)