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.
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
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.
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.
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);
}
}
}
- For returning Index view which showing – Index()
- Action for adding the record in the database– AddPatient()
- For Updating Patient records in the database– UpdatePatient()
- 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.
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
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.
The post How to make an Inline editable table in MVC using jquery? appeared first on Software Development | Programming Tutorials.
Read More Articles
- Write a value which contain comma to a CSV file in c#?
- Reading CSV File with cells containing commas c#
- Split CSV with columns may contain ‘,’ Comma C#
- [Simple Way]-Cascading DropDownList in Asp.Net Mvc Using Jquery Ajax
- [Simple Way]-How to get data from database using JQuery Ajax in asp net MVC
- [Simple Way]-ASP.NET Core Upload Multiple File Web API model
- [Simple Way]- Image Upload in .NET Core Web API
- [Easy Way]-Receive File and other form data together in ASP.NET Core Web API
- Replace image in word document using C#
- How to add new rows to an existing word document table in C#
- How to make the table non breaking using iTextSharp
- How to set inline css width using model values in c#, mvc
- How to post viewmodel in MVC using jquery
- Kendo MVC Grid - How to make cell Editable based on a model value
- How to load HTML Table in MVC using ViewData?
- How to custom user table in MVC 5 using identity?
- How do I make calls to a REST API using C#?
- How can I change the table names when using ASP.NET Identity?
- How to make sure that string is valid JSON using JSON.NET
- Passing A List Of Objects Into An MVC Controller Method Using jQuery Ajax
- How to make inline functions in C#
- How do I mock the HttpContext in ASP.NET MVC using Moq?
- How to post an array of complex objects with JSON, jQuery to ASP.NET MVC Controller?
- How to monitor SQL Server table changes by using c#?
- When using .net MVC RadioButtonFor(), how do you group so only one selection can be made?
- How to make Check Box List in ASP.Net MVC
- How to sync model after using Code First from Database using Entity Framework 6.1 and MVC 5?
- How do I iterate through rows in an excel table using epplus?
- How can I make a TextBox be a "password box" and display stars when using MVVM?
- How do you clear cookies using asp.net mvc 3 and c#?
- How could I make my RavenDB application execute properly when UseEmbeddedHttpServer is set to true using 2-tier architecture?
- how to make a wizard with ASP.Net MVC
- How to upload large files using MVC 4?
- How Can I Hide Kendo UI Grid Columns using JavaScript, React, Angular, Vue or ASP.NET MVC
- How do I route images using ASP.Net MVC routing?
- How to make convert a Month or Day to reflect as a 2 digit string using C#
- How do I resolve Web API controllers using Autofac in a mixed Web API and MVC application?
- How to resolve un-registered type using standard MVC Core dependency injection
- How do I make my own method similar to String.Format using Composite Formatting in C#
- How can I centralize modelstate validation in asp.net mvc using action filters?
- How to make the datagridview line text in bold when I pick a row?
- Inno Setup for Windows service?
- DataGridView - how to set the currency format for a single column ONLY
- TcpListener vs SocketAsyncEventArgs
- An error occurred while creating a route
- Simplest way to deserialize an Array/Sequence of objects from XML with C#?
- HTTP Post as IE6 using C#
- Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and <null>
- How to create a snk from pfx / cer?
- Using multiple instances of MemoryCache
- Set NullValueHandling at a controller level
- UWP grid to fill parent window
- How do I Unit Test the correct view is returned with MVC ASP.Net?
- Pros and cons of RNGCryptoServiceProvider
- Programmatically change Dropdown Menu Options in Unity3D
- String.StartsWith not working with Asian languages?
- Should a setter return immediately if assigned the same value?
- Unable to set datetime format in MVC 4 using data annotations
- Change href link in content place holder from C# code
- How do I allow HTML tags to be submitted in a textbox in asp.net?