In my last article, we have discussed Insert Update Delete Using Jquery Ajax and Modal Popup in MVC. In this post, We will do add edit records using partial view jquery and bootstrap popup modal in asp net MVC.
So Let’s start, step by step to learn,In this post, We will create a Home View where Admin can manage the teacher’s records.
We’ll be creating a table grid that will have some basic operations like Add, Update and Delete rows using the Dialog javascript confirmation alert box.
Step-1 : Create a database named “DotNetPeTips” in your local SQL server.
I have created a table called Teacher with column Id, Teacher_Name, Teacher_Email, Teacher_ContactNo, Teacher_Department, and Teacher_Address.you can execute the below script of the table you can use for practice purposes.
Table Script
CREATE TABLE [dbo].[Teacher](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Teacher_Name] [nvarchar](100) NULL,
[Teacher_Email] [nvarchar](max) NOT NULL,
[Teacher_ContactNo] [nvarchar](14) NULL,
[Teacher_Department] [nvarchar](100) NOT NULL,
[Teacher_Address] [nvarchar](100) NOT NULL,
CONSTRAINT [PK__Teacher__3214EC077B0B6A86] PRIMARY KEY CLUSTERED
(
[Id] ASC
)
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
Step-2 : Add empty MVC project
Step-3 : Add EntityFramework in the project
let’s add an entity data model named “Dotnetpetips.edmx” for performing database operations in the table.
you can Follow the below steps if you are new to the entity framework
Open Vissual=>Go to Solution Explorer => right-click on the project ,Select to Add New item => select ADO.NET Entity Data Model under data in the left side menu. give the model name => Add. and then follow the step described in the below image.
under Dotnetpetips.edmx you open Teacher.cs
namespace PartialViewCrud.Models
{
using System;
using System.Collections.Generic;
public partial class Teacher
{
public int Id { get; set; }
public string Teacher_Name { get; set; }
public string Teacher_Email { get; set; }
public string Teacher_ContactNo { get; set; }
public string Teacher_Department { get; set; }
public string Teacher_Address { get; set; }
}
}
we will use this model clas for binding our view.
Step 4. Creating Controller
Now let’s add a controller for return view, Add a controller named “Teacher”, Right-click on the Controller folder in the project, and click on add an empty controller.
TeacherController.cs
using PartialViewCrud.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace PartialViewCrud.Controllers
{
public class TeacherController : Controller
{
// GET: Teacher
private DotNetPeTipsEntities db = new DotNetPeTipsEntities();
public ActionResult Index()
{
return View();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
Step 5. Creating View
Now Right-click on Index ActionMethod, add empty View.
please make sure to check “Use a Layout page” option. it will create the layout and Bootsrap files for our project.

Step 6. Now let’s add partial view for performing add and edit operations
Just Right click on Shared folder(inside views folder) and add=>view
- checkmark “create a partial view” option ,
- named “_AddTeacher”.
similarly add view for updating the records.
If you are an asp.net web developer, you will recognize that partial views in MVC are alike to user controls in .net web forms.
Partial views are used to encapsulate re-usable view logic and are a great tool to simplify the complexity of views.
These partial views can be used on multiple views, where we require similar visual logic. If you are using the webform view engine, then partial views have an extension of .ascx.
If the visual engine is the razor and the programming language is c #, then partial views have an extension of .cshml.
On the other hand, if the programming language is Visual Basic, the extension is .vbhtml. Please note that partial views can be added to a “shared” folder or to a specific view folder.
Partial views inside the shared folder are available for all views in the project, you can say that partial views inside shared are Global Views. where partial views in a specific folder are only available for views inside that folder which means limited to the specific folder.
Step 7 : Open teacher controller and copy paste the below code
TeacherController.cs
using PartialViewCrud.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace PartialViewCrud.Controllers
{
public class TeacherController : Controller
{
// GET: Teacher
private DotNetPeTipsEntities db = new DotNetPeTipsEntities();
public ActionResult Index()
{
return View();
}
public JsonResult GetAllTeachers()
{
return Json(db.Teachers.ToList(), JsonRequestBehavior.AllowGet);
}
public ActionResult LoadEditTeacherPopup(int TeacherId)
{
try
{
var model = db.Teachers.Where(a => a.Id == TeacherId).FirstOrDefault();
return PartialView("_UpdateTeacher", model);
}
catch (Exception ex)
{
return PartialView("_UpdateTeacher");
}
}
public ActionResult LoadaddTeacherPopup()
{
try
{
return PartialView("_AddTeacher");
}
catch (Exception ex)
{
return PartialView("_AddTeacher");
}
}
public JsonResult AddTeacher(Teacher teachers)
{
string status = "success";
try
{
db.Teachers.Add(teachers);
db.SaveChanges();
}
catch (Exception ex)
{
status = ex.Message;
}
return Json(status, JsonRequestBehavior.AllowGet);
}
public JsonResult UpdateTeacher(Teacher teacher)
{
string status = "success";
try
{
db.Entry(teacher).State = EntityState.Modified;
db.SaveChanges();
}
catch (Exception ex)
{
status = ex.Message;
}
return Json(teacher, JsonRequestBehavior.AllowGet);
}
public JsonResult DeleteTeacher(int TeacherId)
{
string status = "success";
try
{
var pateint = db.Teachers.Find(TeacherId);
db.Teachers.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);
}
}
}
Step 8: Change RouteConfig.cs
change defaults controller name to “Teacher”
Now Open Index.cshtml and Copy paste the below code
Index.cshtml
@{
ViewBag.Title = "Index";
}
<h2>Teacher Record</h2>
@* Table for showing the list of teachers from the database *@
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal" onclick="OpenAddPopup();">Add New Teacher</button><br /><br />
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>
ID
</th>
<th>
Name
</th>
<th>
Email
</th>
<th>
Number
</th>
<th>
Address
</th>
<th>
Department
</th>
<th>
Action
</th>
</tr>
</thead>
<tbody class="tbody"></tbody>
</table>
<div id="divcontent">
</div>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
BindteacherData();
});
function BindteacherData() {
$.ajax({
url: "/Teacher/GetAllTeachers",
type: "GET",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
if (result) {
//itetrate thorugh each record and bind it to td
var html = '';
$.each(result, function (key, item) {
html += '<tr>';
html += '<td>' + item.Id + '</td>';
html += '<td>' + item.Teacher_Name + '</td>';
html += '<td>' + item.Teacher_Email + '</td>';
html += '<td>' + item.Teacher_ContactNo + '</td>';
html += '<td>' + item.Teacher_Address + '</td>';
html += '<td>' + item.Teacher_Department + '</td>';
html += '<td><a href="#" onclick="return OpenUpdatePopup(' + item.Id + ')">Edit</a> | <a href="#" onclick="DeleleTeacher(' + item.Id + ')">Delete</a></td>';
html += '</tr>';
});
$('.tbody').html(html);
}
},
error: function (errormessage) {
alert(errormessage.responseText);
}
});
}
function OpenAddPopup()
{
$.ajax({
url: '/Teacher/LoadaddTeacherPopup',
contentType: 'application/html; charset=utf-8',
type: 'GET',
dataType: 'html',
success: function (result) {
$('#divcontent').empty();
$('#divcontent').html(result);
$('#AddUpdateModelPopup').modal('show');
},
error: function (xhr, status) {
alert(status);
}
})
}
function OpenUpdatePopup(Id) {
$.ajax({
url: '/Teacher/LoadEditTeacherPopup?TeacherId=' + Id,
contentType: 'application/html; charset=utf-8',
type: 'GET',
dataType: 'html',
success: function (result) {
$('#divcontent').empty();
$('#divcontent').html(result);
$('#AddUpdateModelPopup').modal('show');
//$('#btndivuserguidemodel').trigger('click');
},
error: function (xhr, status) {
alert(status);
}
})
}
//Add Data Function
function AddTeacher() {
var res = ValidateForm();
if (res == false) {
return false;
}
var TeacherObj = {
Id: $('#Id').val(),
Teacher_Name: $('#Teacher_Name').val(),
Teacher_Email: $('#Teacher_Email').val(),
Teacher_ContactNo: $('#Teacher_ContactNo').val(),
Teacher_Department: $('#Teacher_Department').val(),
Teacher_Address: $('#Teacher_Address').val(),
};
$.ajax({
url: "/Teacher/AddTeacher",
data: JSON.stringify(TeacherObj),
type: "POST",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
//populate table with new record
BindteacherData();
$('#AddUpdateModelPopup').modal('hide');
},
error: function (errormessage) {
alert(errormessage.responseText);
}
});
}
//function for updating Patient record
function UpdateTeacher() {
var res = ValidateForm();
if (res == false) {
return false;
}
var TeacherObj = {
Id: $('#Id').val(),
Teacher_Name: $('#Teacher_Name').val(),
Teacher_Email: $('#Teacher_Email').val(),
Teacher_ContactNo: $('#Teacher_ContactNo').val(),
Teacher_Department: $('#Teacher_Department').val(),
Teacher_Address: $('#Teacher_Address').val(),
};
if (!TeacherObj.Id || TeacherObj.Id <= 0) {
alert("Invalid Id!");
return false;
}
$.ajax({
url: "/Teacher/UpdateTeacher",
data: JSON.stringify(TeacherObj),
type: "POST",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
BindteacherData();
$('#AddUpdateModelPopup').modal('hide');
},
error: function (errormessage) {
alert(errormessage.responseText);
}
});
}
//function for deleting Teacher's record
function DeleleTeacher(ID) {
var ans = confirm("Are you sure you want to delete?");
if (ans) {
$.ajax({
url: "/Teacher/DeleteTeacher?TeacherId=" + ID,
type: "POST",
contentType: "application/json;charset=UTF-8",
dataType: "json",
success: function (result) {
BindteacherData();
},
error: function (errormessage) {
alert(errormessage.responseText);
}
});
}
}
function ValidateForm() {
var isValid = true;
if ($('#Teacher_Name').val().trim() == "") {
$('#Teacher_Name').css('border-color', 'Red');
isValid = false;
}
else {
$('#Teacher_Name').css('border-color', 'lightgrey');
}
if ($('#Teacher_Email').val().trim() == "") {
$('#Teacher_Email').css('border-color', 'Red');
isValid = false;
}
else {
$('#Teacher_Email').css('border-color', 'lightgrey');
}
if ($('#Teacher_ContactNo').val().trim() == "") {
$('#Teacher_ContactNo').css('border-color', 'Red');
isValid = false;
}
else {
$('#Teacher_ContactNo').css('border-color', 'lightgrey');
}
if ($('#Teacher_Department').val().trim() == "") {
$('#Teacher_Department').css('border-color', 'Red');
isValid = false;
}
else {
$('#Teacher_Department').css('border-color', 'lightgrey');
}
if ($('#Teacher_Address').val().trim() == "") {
$('#Teacher_Address').css('border-color', 'Red');
isValid = false;
}
else {
$('#Teacher_Address').css('border-color', 'lightgrey');
}
return isValid;
}
</script>
_AddTeacher.cshtml
@model PartialViewCrud.Models.Teacher
<div class="modal fade" id="AddUpdateModelPopup" 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 Records</h4>
</div>
<div class="modal-body">
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@* Hidden filed for storing Id of teacher need to be updated *@
@Html.HiddenFor(model => model.Id)
<div class="form-group">
@Html.LabelFor(model => model.Teacher_Name, htmlAttributes: new { @class = "control-label col-md-4" })
<div class="col-md-8">
@Html.EditorFor(model => model.Teacher_Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Teacher_Name, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Teacher_Email, htmlAttributes: new { @class = "control-label col-md-4", })
<div class="col-md-8">
@Html.EditorFor(model => model.Teacher_Email, new { htmlAttributes = new { @class = "form-control", @type = "email" } })
@Html.ValidationMessageFor(model => model.Teacher_Email, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Teacher_ContactNo, htmlAttributes: new { @class = "control-label col-md-4" })
<div class="col-md-8">
@Html.EditorFor(model => model.Teacher_ContactNo, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Teacher_ContactNo, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Teacher_Department, htmlAttributes: new { @class = "control-label col-md-4" })
<div class="col-md-8">
@Html.EditorFor(model => model.Teacher_Department, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Teacher_Department, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Teacher_Address, htmlAttributes: new { @class = "control-label col-md-4" })
<div class="col-md-8">
@Html.EditorFor(model => model.Teacher_Address, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Teacher_Address, "", new { @class = "text-danger" })
</div>
</div>
</div>
}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" id="btnUpdateteacher" onclick="return AddTeacher();">Add Teacher</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
_UpdateTeacher.cshtml
@model PartialViewCrud.Models.Teacher
<div class="modal fade" id="AddUpdateModelPopup" 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">Update Records</h4>
</div>
<div class="modal-body">
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@* Hidden filed for storing Id of teacher need to be updated *@
@Html.HiddenFor(model => model.Id)
<div class="form-group">
@Html.LabelFor(model => model.Teacher_Name, htmlAttributes: new { @class = "control-label col-md-4" })
<div class="col-md-8">
@Html.EditorFor(model => model.Teacher_Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Teacher_Name, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Teacher_Email, htmlAttributes: new { @class = "control-label col-md-4", })
<div class="col-md-8">
@Html.EditorFor(model => model.Teacher_Email, new { htmlAttributes = new { @class = "form-control", @type = "email" } })
@Html.ValidationMessageFor(model => model.Teacher_Email, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Teacher_ContactNo, htmlAttributes: new { @class = "control-label col-md-4" })
<div class="col-md-8">
@Html.EditorFor(model => model.Teacher_ContactNo, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Teacher_ContactNo, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Teacher_Department, htmlAttributes: new { @class = "control-label col-md-4" })
<div class="col-md-8">
@Html.EditorFor(model => model.Teacher_Department, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Teacher_Department, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Teacher_Address, htmlAttributes: new { @class = "control-label col-md-4" })
<div class="col-md-8">
@Html.EditorFor(model => model.Teacher_Address, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Teacher_Address, "", new { @class = "text-danger" })
</div>
</div>
</div>
}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" id="btnUpdateteacher" onclick="return UpdateTeacher();">Update Teacher</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
The post CRUD operation using partial view in MVC with modal popup 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#
- Simple Way Find and replace text in Word document using C#
- Implementing “Remember Me” Feature in ASP.NET MVC
- [Solved]-Cookie loses value when page is changed in MVC
- How to post File Upload and other form fields to one action Asp .Net MVC C#
- How To Post File and Data to API using HttpClient C#
- Create ASP.NET Core Web API Without Entity Framework
- .NET Core Web API Using Code First Entity Framework Approach
- Create Asp.Net Core Web Api Using Entity Framework Database First
- Registration form with image upload in MVC using jquery Ajax
- How to make an Inline editable table in MVC using jquery?
- CRUD operation using partial view in MVC with modal popup
- Insert Update Delete Using Jquery Ajax and Modal Popup in Mvc
- Crud Operations in MVC Without Entity Framework
- Create Login,Signout and Registration in Asp .Net Mvc Using Entity
- Export Gridview to Excel and Csv in Asp .Net With Formatting Using c#
- How to Display Binary Image in Gridview from Database in Asp .Net c#
- [Solved]-How to Upload pdf file using jquery MVC?
- [Solved]-Uploading both data and files in FormData using Ajax MVC
- C# -Saving a base64 string as an image into a folder on server in Web Api
- [Solved]-Download pdf file from link and save in local file folder in Asp .Net
- [Solved]-Delete Files older than X Months,Days,Minute in a Directory- C# .NET
- [Solved]-LEFT OUTER JOIN in LINQ With Where clause in C#
- INNER JOIN,RIGHT JOIN,LEFT JOIN USING LINQ IN Multiple Table C#
- [Solved]-Convert Base64 To Image And Save in folder and Display it- C#
- [Solved]-How to Overlay Two Images in .NET-C#
- How to Create Multilingual Website in Asp .Net
- C# – How to add double quotes to a string that is inside a variable
- Update an Image with Upload Button For Each Row in Gridview-Asp .Net
- How to Bind Data in DataList Control in Asp.Net – C#
- Upload and Display an Image in Gridview From Image Path in Database -C#