Inline Editing of a table

How to make an Inline editable table in MVC using jquery?

Accessing Data from a database is an important phase of any programming language. Any programming language must have the ability to work with databases. ASP.Net MVC can work with different types of databases. It can operate with common databases such as Mysql, MongoDB, Oracle, and Microsoft SQL Server.

Sometimes in our, we need to insert, update and delete records(crud) in a Table Gridview using inline editing.Suppose I have one web page in which I can see the list of users in our system and we need to insert, view, update and delete user records. To do that, instead of creating 4 webpages to perform these tasks we can create a single view to satisfy requirements. so in this we will perform  add, edit and delete rows of a HTML table with jquery in MVC .let’s do that.

Download Source Code

In this post, we will learn-

  • MVC CRUD operation usiing Table with Inline Editor
  • Spring ASP .Net MVC editable table example
  • How to perform inline editing of a cell in table in an Asp .Net MVC application

Tables are a fundamental part of the user interface that helps users visualize big data in an arranged way. Using experience for data tables is an easy task when you are working with MVC.

Data Tables contain a number of elements including paging, editing, filtering, sorting, show / hidden columns, search, etc., so developers don’t need to take care of when designing tables. This post describes ways to display input validation messages when users are doing inline editing.

Inline editing provides a way to edit table contents while staying within the same page without navigating to another web page or pop-up. Users can just click on a row or cell and edit their data. This feature helps users to quickly change the content without moving away from the current webpage. This is a most comfortable and quick way to edit the contents of a table.

I have written this post especially focusing on new developers who just started learning the MVC and want to insert, update and delete records in a table using inline editing.

Step 1- Create database table

so let us start with a basic introduction, I have created a table in our local database and I have set the primary key on the id column and set the Identity specification to Yes.

I have created a table called Teacher with column Id, PatientName, PatientNumber, PatientEmail, Address, and BloodGroup.you can execute the below script of the table you can use for practice purposes.

CREATE TABLE [dbo].[TblPatient](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[PatientName] [nvarchar](250) NULL,
	[PatientNumber] [nvarchar](100) NULL,
	[PatientEmail] [nvarchar](150) NULL,
	[Address] [nvarchar](500) NULL,
	[BloodGroup] [nvarchar](100) NULL,
 CONSTRAINT [PK_TblPatient] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)
) ON [PRIMARY]

Step-2 : Add empty MVC project

Follow step mention in the Image

Create An Mvc Project

Step 3- Now Add EntityFramework in the project

Follow the below step diagram if you are new to the entity framework.
Right-click on the Model folder and select add a new item =>select Ado .net entity data model from the option and perform the steps described in the below image.

Create a Entity Framework

Step 4. Add Controller

Now let’s add a controller for performing crud operation, Right-click on the Controller folder and click on add an empty controller. I have created controller with Patient named you can give you choice name.

Create a Controller

Copy Paste Below Code in the controller

PatientController.cs

using CrudJqueryAjax.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CrudJqueryAjax.Controllers
{
    public class PatientController : Controller
    {
        // GET: Patient
        private SampleRestApiEntities db = new SampleRestApiEntities();

        // GET: Patient
        public ActionResult Index()
        {
            return View(db.TblPatients.ToList());

        }
        public JsonResult AddPatient(TblPatient tblPatient)
        {
            try
            {
                db.TblPatients.Add(tblPatient);
                db.SaveChanges();
            }
            catch(Exception ex)
            {
               
            }
            return Json(tblPatient, JsonRequestBehavior.AllowGet);

        }
        public JsonResult UpdatePatient(TblPatient tblPatient)
        {

            string status = "success";
            try
            {
                db.Entry(tblPatient).State = EntityState.Modified;
                db.SaveChanges();

            }
            catch (Exception ex)
            {
                status = ex.Message;

            }
            return Json(tblPatient, JsonRequestBehavior.AllowGet);
        }
        public JsonResult DeletePatient(int PatientId)
        {
            string status = "success";
            try
            {

                var pateint = db.TblPatients.Find(PatientId);
                db.TblPatients.Remove(pateint);
                db.SaveChanges();

            }
            catch (Exception ex)
            {
                status = ex.Message;

            }
            return Json(status, JsonRequestBehavior.AllowGet);
        }
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
  1. For returning Index view which showing – Index()
  2. Action for adding the record in the database– AddPatient()
  3. For Updating Patient records in the database– UpdatePatient()
  4. For deleting a Patient  record in the database– DeletePatient ()

Step 5. Creating Index View

In PatientController.cs  ,Right-click on Index ActionMethod, add empty View, check “Use a Layout page” option. it will add the layout and Bootsrap files in our project.

AddIndexView-1

AddBootstrap

Now Open Index.cshtml and Copy paste the below code

Index.cshtml

 

@model IEnumerable<CrudJqueryAjax.Models.TblPatient>
@{
    ViewBag.Title = "Index";
}
<h2>Patient Record</h2>
@* Table for showing the list of Records from the database *@
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal" onclick="OpenAddPopup();">Add New Patient</button><br /><br />
<table class="table table-bordered table-hover" id="datatable">
    <thead>
        <tr>
            <th>
                Patient ID
            </th>
            <th>
                PatientName
            </th>
            <th>
                PatientNumber
            </th>
            <th>
                PatientEmail
            </th>
            <th>
                Address
            </th>
            <th>
                BloodGroup
            </th>
            <th>
                Action
            </th>
        </tr>
    </thead>
    <tbody class="tbody" id="tblbody">
        @foreach (var item in Model)
        {
            <tr>
                <td class="PatientId">
                    <span>@item.Id</span>
                </td>
                <td class="PatientName">
                    <span>@item.PatientName</span>
                    <input type="text" value="@item.PatientName" style="display:none" />
                </td>
                <td class="PatientNumber">
                    <span>@item.PatientNumber</span>
                    <input type="text" value="@item.PatientNumber" style="display:none" />
                </td>
                <td class="PatientEmail">
                    <span>@item.PatientEmail</span>
                    <input type="email" value="@item.PatientEmail" style="display:none" />
                </td>
                <td class="Address">
                    <span>@item.Address</span>
                    <input type="text" value="@item.Address" style="display:none" />
                </td>
                <td class="BloodGroup">
                    <span>@item.BloodGroup</span>
                    <input type="text" value="@item.BloodGroup" style="display:none" />
                </td>
                <td>
                    <a class="btnEdit" href="javascript:;">Edit</a>
                    <a class="btnUpdate" href="javascript:;" style="display:none">Update</a>
                    <a class="btnCancel" href="javascript:;" style="display:none">Cancel</a>
                    <a class="btnDelete" href="javascript:;">Delete</a>
                </td>
            </tr>
        }
    </tbody>
</table>

@*BootsTrap Model Popup for Adding and Updating the  Patient Record *@
<div class="modal fade" id="AddUpdateModel" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">×</button>
                <h4 class="modal-title" id="AddUpdateModelLabel">Add Patient</h4>
            </div>
            <div class="modal-body">
                <form>
                    @* hidden filed for storing Id *@
                    <input type="hidden" id="hfpatientId" />
                    <div class="form-group">
                        <label for="txtPatientName">Patient Name</label>
                        <input type="text" class="form-control" id="txtPatientName" placeholder="Patient Name" />
                    </div>
                    <div class="form-group">
                        <label for="txtPatientNumber">Patient Number</label>
                        <input type="text" class="form-control" id="txtPatientNumber" placeholder="Patient Number" />
                    </div>
                    <div class="form-group">
                        <label for="txtPatientEmail">Patient Email</label>
                        <input type="email" class="form-control" id="txtPatientEmail" placeholder="Patient Email" />
                    </div>
                    <div class="form-group">
                        <label for="txtAddress">Address</label>
                        <input type="text" class="form-control" id="txtAddress" placeholder="Address" />
                    </div>
                    <div class="form-group">
                        <label for="txtBloodGroup">BloodGroup</label>
                        <input type="text" class="form-control" id="txtBloodGroup" placeholder="BloodGroup" />
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" id="btnAddpatient" onclick="return AddPatient();">Create Patient</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>

<script type="text/javascript">
    function AppendRowAfterInsertRecord(row, PatientId, name, PatientNumber, PatientEmail, Address, BloodGroup) {
        //Bind CustomerId.
        $(".PatientId", row).find("span").html(PatientId);

        //Bind Name.
        $(".PatientName", row).find("span").html(name);
        $(".PatientName", row).find("input").val(name);

        //Bind Country.
        $(".PatientNumber", row).find("span").html(PatientNumber);
        $(".PatientNumber", row).find("input").val(PatientNumber);

        //Bind Country.
        $(".PatientEmail", row).find("span").html(PatientEmail);
        $(".PatientEmail", row).find("input").val(PatientEmail);

        //Bind Country.
        $(".Address", row).find("span").html(Address);
        $(".Address", row).find("input").val(Address);

        //Bind Country.
        $(".BloodGroup", row).find("span").html(BloodGroup);
        $(".BloodGroup", row).find("input").val(BloodGroup);
        debugger;
        row.find(".btnEdit").show();
        row.find(".btnDelete").show();
        $("#datatable").append(row);
    };

    //Edit event handler.
    $("body").on("click", "#datatable .btnEdit", function () {
        debugger;
        var row = $(this).closest("tr");
        $("td", row).each(function () {
            if ($(this).find("input").length > 0) {
                $(this).find("input").show();
                $(this).find("span").hide();
            }
        });
        row.find(".btnUpdate").show();
        row.find(".btnCancel").show();
        row.find(".btnDelete").hide();
        $(this).hide();
    });

    //Update event handler.
    $("body").on("click", "#datatable .btnUpdate", function () {
        var row = $(this).closest("tr");
        $("td", row).each(function () {
            if ($(this).find("input").length > 0) {
                var span = $(this).find("span");
                var input = $(this).find("input");
                span.html(input.val());
                span.show();
                input.hide();
            }
        });
        row.find(".btnEdit").show();
        row.find(".btnDelete").show();
        row.find(".btnCancel").hide();
        $(this).hide();

        var patientObj = {
            Id: row.find(".PatientId").find("span").html(),
            PatientName: row.find(".PatientName").find("span").html(),
            PatientNumber: row.find(".PatientNumber").find("span").html(),
            PatientEmail: row.find(".PatientEmail").find("span").html(),
            Address: row.find(".Address").find("span").html(),
            BloodGroup: row.find(".BloodGroup").find("span").html(),
        };
        if (!patientObj.Id || patientObj.Id <= 0) {
            alert("Invalid Id!");
            return false;
        }
        $.ajax({
            url: "/Patient/UpdatePatient",
            data: JSON.stringify(patientObj),
            type: "POST",
            contentType: "application/json;charset=utf-8",
            dataType: "json",
            success: function (result) {
                ClearAllInput();
            },
            error: function (errormessage) {
                alert(errormessage.responseText);
            }
        });
    });

    //Cancel event handler.
    $("body").on("click", "#datatable .btnCancel", function () {
        var row = $(this).closest("tr");
        $("td", row).each(function () {
            if ($(this).find("input").length > 0) {
                var span = $(this).find("span");
                var input = $(this).find("input");
                input.val(span.html());
                span.show();
                input.hide();
            }
        });
        row.find(".btnEdit").show();
        row.find(".btnDelete").show();
        row.find(".btnUpdate").hide();
        $(this).hide();
    });

    //Delete event handler.
    $("body").on("click", "#datatable .btnDelete", function () {
        if (confirm("Do you want to delete this row?")) {
            var row = $(this).closest("tr");
            var PatientId = row.find("span").html();
            $.ajax({
                url: "/Patient/DeletePatient?PatientId=" + PatientId,
                type: "POST",
                contentType: "application/json;charset=UTF-8",
                dataType: "json",
                success: function (response) {
                    if ($("#datatable tr").length > 2) {
                        row.remove();
                    } else {
                        row.find(".btnEdit").hide();
                        row.find(".btnDelete").hide();
                        row.find("span").html(' ');
                    }
                }
            });
        }
    });


    function OpenAddPopup() {
        //title text
        $("#AddUpdateModelLabel").text("Add Patient")
        //clear all input
        ClearAllInput();
        //open popup
        $('#AddUpdateModel').modal('show');
    }

    //Add Data Function
    function AddPatient() {
        var res = ValidateUserInput();
        if (res == false) {
            return false;
        }
        var patientObj = {
            Id: $('#hfpatientId').val(),
            PatientName: $('#txtPatientName').val(),
            PatientNumber: $('#txtPatientNumber').val(),
            PatientEmail: $('#txtPatientEmail').val(),
            Address: $('#txtAddress').val(),
            BloodGroup: $('#txtBloodGroup').val(),
        };
        $.ajax({
            url: "/Patient/AddPatient",
            data: JSON.stringify(patientObj),
            type: "POST",
            contentType: "application/json;charset=utf-8",
            dataType: "json",
            success: function (result) {
                debugger;
               
                //populate table with new record
                var row = $("#tblbody tr:last-child");
                if ($("#tblbody tr:last-child span").eq(1).html() != " ")
                {
                    row = row.clone();
                }
              
                AppendRowAfterInsertRecord(row, result.Id, result.PatientName, result.PatientNumber,
                    result.PatientEmail, result.Address, result.BloodGroup);
                $('#AddUpdateModel').modal('hide');
                //claer all input and hide model popup
                ClearAllInput();
            },
            error: function (errormessage) {
                alert(errormessage.responseText);
            }
        });
    }
    function ClearAllInput() {
        $('#AddUpdateModel').modal('hide');
        $('#hfpatientId').val("");
        $('#txtPatientName').val("");
        $('#txtPatientNumber').val("");
        $('#txtPatientEmail').val("");
        $('#txtAddress').val("");
        $('#txtBloodGroup').val("");

        $('#txtPatientName').css('border-color', 'lightgrey');
        $('#txtPatientNumber').css('border-color', 'lightgrey');
        $('#txtPatientEmail').css('border-color', 'lightgrey');
        $('#txtAddress').css('border-color', 'lightgrey');
        $('#txtBloodGroup').css('border-color', 'lightgrey');
    }

    function ValidateUserInput() {
        var isValid = true;
        if ($('#txtPatientName').val().trim() == "") {
            $('#txtPatientName').css('border-color', 'Red');
            isValid = false;
        }
        else {
            $('#txtPatientName').css('border-color', 'lightgrey');
        }
        if ($('#txtPatientNumber').val().trim() == "") {
            $('#txtPatientNumber').css('border-color', 'Red');
            isValid = false;
        }
        else {
            $('#txtPatientNumber').css('border-color', 'lightgrey');
        }
        if ($('#txtPatientEmail').val().trim() == "") {
            $('#txtPatientEmail').css('border-color', 'Red');
            isValid = false;
        }
        else {
            $('#txtPatientEmail').css('border-color', 'lightgrey');
        }
        if ($('#txtAddress').val().trim() == "") {
            $('#txtAddress').css('border-color', 'Red');
            isValid = false;
        }
        else {
            $('#txtAddress').css('border-color', 'lightgrey');
        }

        if ($('#txtBloodGroup').val().trim() == "") {
            $('#txtBloodGroup').css('border-color', 'Red');
            isValid = false;
        }
        else {
            $('#txtBloodGroup').css('border-color', 'lightgrey');
        }
        return isValid;
    }
</script>

 

Step 7- Change Configure RouteConfig.cs file

Open RouteConfig.cs file in App_Start folder and Change controller name from to Patient
Routeconfig

Now Build project and run in the browser
Download Source Code

Bootstrap is absolutely free and you will not have to pay any charge to use it.Designing a website in Bootstrap is very quick and easy. Responsive means that this website is flexible for all devices i.e the device in which we open the website will fit according to the device screen size.

Bootstrap was created in mid-2010. Initially, Bootstrap was named Twitter blueprint. Before the open-source, Bootstrap was used in the Twitter company.

On 19 August 2011, Bootstrap was launched to the public. Since launch, there have been more than 20 version releases of Bootstrap so far.

Why is Bootstrap Used?
Developing a website with help of bootstrap is very simple and quick. Websites made in Bootstrap are fast and attractive.
Forms, Tables, Navigations, Buttons, etc. can be made very easily and beautifully in Bootstrap.

Features of Bootstrap

Responsive Features:
Websites created in Bootstrap are Responsive i.e. get adjusted on Phones, Tablets, Computers.

Customizable:
Bootstrap is Open Source that’s why Fully Customizable.
With Bootstrap, you can redesign your website according to your project and requirements.

Mobile-Friendly:
Mobile-First approach, Bootstrap v3 used mobile-first style.

Easy to use:
Bootstrap is very easy to use.
Anyone with a primary understanding of HTML, CSS can start using Bootstrap

Free to use:
Bootstrap is a free project. Any such can be used for free.

Attractive Design:
Websites made in Bootstrap are very attractive and modern.

Browser Compatibility:
Bootstrap export with all modern browsers like Chrome, Firefox, Internet Explorer, Safari, and Opera.

Great Grid System:
Bootstrap consists of the Grid System and can go to 12 Responsive Grids.

Ashok Patel

I'm an electronic engineer working in a multinational company,having good experience on Electronics and electrical engineers design and oversee production of electronic equipment such as radios, televisions, computers, washing machines and telecommunication systems.I like to do RND and Research.I also have hands on experience graphic design software and in web designing having great command on ASP.NET, HTML5, JavaScript, T-SQL, JQuery.

Add comment

Your Header Sidebar area is currently empty. Hurry up and add some widgets.