CRUD Operation Using TypeScript In ASP.NET MVC 5

Here, we will learn about how to perform CRUD Operation using TypeScript in ASP.NET MVC 5. CRUD Operation is the basics for all the web applications. We have already seen how to integrate TypeScript in ASP.NET MVC 5 project. If you haven’t referred it then you can read it from here.

Roadmap for developing the application

  • Configure TypeScript in ASP.NET MVC 5 Project
  • Setting up NuGet packages and Database connection
  • Making our controller for CRUD Operation
  • TypeScript code for performing CRUD Operation
  • Using the TypeScript in our ASP.NET application
  • Code in Action

Configure TypeScript in ASP.NET MVC 5 Project

Create a new tsconfig.json file also know as TypeScript Configuration file. You can see it from here on how to set up it.

Setting up NuGet packages and Database connection

For CRUD operation, we are going to use Entity Framework. You can install it from NuGet package console by typing the command.

Install-Package EntityFramework

Open the web config file and add the following connection string in it. Kindly change the username and password with your’s

<connectionStrings>
    <add name="DefaultConnection" connectionString="data source=******;user id=**;password=******;initial catalog=CodeHubsAPIDB;integrated security=True;" providerName="System.Data.SqlClient" />
  </connectionStrings>

Create a folder named Entity in our project solution and include the database context file named CodeHubsAPIContext.cs in it. Also, create one class file as Users.cs file for users table.

C# code for Users.cs file:

public class Users
    {
        [Key]
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public string Phone { get; set; }
    }

C# code for CodeHubsAPIContext.cs file

public class CodeHubsAPIContext : DbContext
    {
        public CodeHubsAPIContext() : base("DefaultConnection") { }
        public DbSet<Users> Users { get; set; }
    }

After setting up the database connections, open the Nuget Package Manager console from Tools and type the following command in it.

Enable-Migrations
Add-Migration Initial
Update-Database

Making our controller for CRUD Operation

Create a new controller named UsersController.cs and add the following code in it.

public class UsersController : Controller
    {
        private readonly CodeHubsAPIContext _context = null;

        public UsersController()
        {
            _context = new CodeHubsAPIContext();
        }

        [Route("api/users")]
        public JsonResult GetUsers() => Json(new { userList = _context.Users.ToList() }, JsonRequestBehavior.AllowGet);

        [Route("api/users/{userId}")]
        public JsonResult GetUserById(int userId) => Json(new { user = _context.Users.FirstOrDefault(x => x.Id == userId) }, JsonRequestBehavior.AllowGet);

        [Route("api/users/modify")]
        public JsonResult AddEditUser()
        {
            try
            {
                var formData = Request.Form;
                string userData = formData["userData"];
                var user = JsonConvert.DeserializeAnonymousType(userData, new Users());
                if (user == null)
                {
                    return Json(new { isSuccess = false, message = "Data not found" }, JsonRequestBehavior.AllowGet);
                }
                if (user.Id == 0)
                {
                    _context.Users.Add(user);
                    _context.SaveChanges();
                    return Json(new { isSuccess = true, message = "User added successfully" }, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    var isUserExist = _context.Users.FirstOrDefault(x => x.Id == user.Id);
                    if (isUserExist == null)
                    {
                        return Json(new { isSuccess = false, message = "User not exist" }, JsonRequestBehavior.AllowGet);
                    }
                    isUserExist.Name = user.Name;
                    isUserExist.Email = user.Email;
                    isUserExist.Phone = user.Phone;
                    _context.SaveChanges();
                    return Json(new { isSuccess = true, message = "User updated successfully" }, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                return Json(new { isSuccess = false, message = ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }

        [Route("api/users/delete")]
        public JsonResult DeleteUserById(int userId)
        {
            var isUserExist = _context.Users.FirstOrDefault(x => x.Id == userId);
            if (isUserExist == null)
            {
                return Json(new { isSuccess = false, message = "User not exist" }, JsonRequestBehavior.AllowGet);
            }
            _context.Users.Remove(isUserExist);
            _context.SaveChanges();
            return Json(new { isSuccess = true, message = "User deleted successfully" }, JsonRequestBehavior.AllowGet);
        }
    }

TypeScript code for performing CRUD Operation

Create a file named app.ts where you have created the tsconfig.json file. Place the following code in it.

var $: any;
var toastr: any;
module CRUDModule {
    export class UserDTO {
        Id: string;
        Name: string;
        Email: string;
        Phone: string;
    }

    export class CrudComponent {

        getUserList() {
            fetch(`/api/users`).then(res => res.json()).then(res => {
                var response: any = res;
                if (response.userList != null) {
                    var userData = response.userList;
                    var tbody = "";
                    for (var i = 0; i < userData.length; i++) {
                        tbody += `<tr>
                                       <td>${userData[i][`Name`]}</td>
                                       <td>${userData[i][`Email`]}</td>
                                       <td>${userData[i][`Phone`]}</td>
                                       <td><i class="fa fa-edit" onclick="getUserById('${userData[i][`Id`]}')"></i><i class="fa fa-times" onclick="deleteUserById('${userData[i][`Id`]}')"></i></td>
                                    <tr>`
                    }
                    $('#tblUsers tbody').html(tbody);
                }
            });
        }

        getUserById(userId: number) {
            fetch(`/api/users/${userId}`).then(res => res.json()).then(res => {
                var response: any = res.user;
                if (response != null) {
                    $('#hdnId').val(response.Id);
                    $('#txtName').val(response.Name);
                    $('#txtEmail').val(response.Email);
                    $('#txtPhone').val(response.Phone);
                    $('#modalUser').modal('show');
                }
            });
        }

        modifyUser(userDTO: UserDTO) {
            var userForm = new FormData();
            userForm.append("userData", JSON.stringify(userDTO));
            fetch(`/api/users/modify`, {
                method: 'POST',
                body: userForm
            }).then(res => res.json()).then(res => {
                var response: any = res;
                if (response.isSuccess == true)
                    toastr.success(response.message);
                else
                    toastr.error(response.message);
                this.getUserList();
                $('#modalUser').modal('hide');
            });
        }

        deleteUserById(userId: number) {
            if (confirm("Are you sure you want to delete the record")) {
                fetch(`/api/users/delete?userId=${userId}`, {
                    method: 'GET'
                }).then(res => res.json()).then(res => {
                    var response: any = res;
                    if (response.isSuccess == true)
                        toastr.success(response.message);
                    else
                        toastr.error(response.message);
                    this.getUserList();
                });
            }
        }
    }
}

Using the TypeScript in our ASP.NET application

Open the _Layout.cshtml file from the Shared folder and place the following code in it.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - TypeScript Crud Operation</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css" />
</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                @Html.ActionLink("TypeScript Crud Operation", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                </ul>
            </div>
        </div>
    </div>
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - TypeScript Crud Operation</p>
        </footer>
    </div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/js/toastr.min.js"></script>
    <script src="~/appScriptsJS/app.js"></script>
    @RenderSection("scripts", required: false)
</body>
</html>

Finally, open the Index.cshtml file from Home folder in View and place the following code in it.

@{
    ViewBag.Title = "Home Page";
}

<style>
    td i {
        margin-left: 10px;
    }

    #btnAddUser {
        margin-bottom: 10px;
        margin-left: auto;
        margin-right: auto;
        display: flex;
    }
</style>

<div class="row" style="margin-top: 80px;">
    <button class="btn btn-success" id="btnAddUser">Add User</button>
    <div class="col-md-12">
        <table id="tblUsers" class="table table-responsive table-bordered table-hover">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Email</th>
                    <th>Phone</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody></tbody>
        </table>
    </div>
</div>

<div class="modal fade" id="modalUser" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title">Add User</h4>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <label>Name</label>
                    <input type="hidden" id="hdnId" value="0" />
                    <input type="text" class="form-control clear-data" id="txtName" />
                </div>
                <div class="form-group">
                    <label>Email</label>
                    <input type="email" class="form-control clear-data" id="txtEmail" />
                </div>
                <div class="form-group">
                    <label>Phone Number</label>
                    <input type="number" class="form-control clear-data" id="txtPhone" />
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" id="btnSaveUser">Save Data</button>
            </div>
        </div>
    </div>
</div>

@section scripts{
    <script>
        var crudComponent = new CRUDModule.CrudComponent();

        $(document).ready(function () {
            crudComponent.getUserList();
        });

        function getUserById(id) {
            crudComponent.getUserById(id);
        }

        function deleteUserById(id) {
            crudComponent.deleteUserById(id);
        }

        $(document).on('click', '#btnAddUser', function () {
            $('#modalUser').modal('show');
        });

        $(document).on('click', '#btnSaveUser', function () {
            var userModal = {
                Id: $('#hdnId').val(),
                Name: $('#txtName').val(),
                Email: $('#txtEmail').val(),
                Phone: $('#txtPhone').val(),
            }
            crudComponent.modifyUser(userModal);
        });

        $("#modalUser").on('hide.bs.modal', function () {
            $('.clear-data').val('');
            $('#hdnId').val('0');
        });
    </script>
}

After all the code, your application structure will look like this.

Code in Action

crud-operation-using-typescript-in-asp-net-mvc-5-output

You can get the source code from my GitHub account from here

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories