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#
- MVC Core, changed root view folder to UI, erroring with "The default Identity UI layout requires a partial view '_LoginPartial'"
- In MVC 3 I have a View with 3 Partial Views. How do i get the 3rd partial view to display on the same page?
- MVC partial view with int model throws exception
- ASP.NET MVC Partial View with different Model
- ASP.NET MVC 5 - Partial view doesn't work with my AJAX live search
- What is the proper way to submit data from Parent form with partial view MVC 4?
- ASP.NET Core 5 MVC Using View Models with enumeration
- Recursion for dynamic menu in ASP.NET Core MVC using partial View
- ASP.Net Core 3.1 - passing value to partial view Modal with Ajax?
- Issue with using two models in the view in ASP.NET MVC
- MVC 4 Model binding with partial view
- Partial View with empty page ASP MVC 3
- ASP.NET MVC 3 partial view not found
- Problems with combined view and IEnumerable model in asp.Net MVC
- Modal Popup not working with AutoCompleteExtender
- Using same partial view for edit and display
- Wait asynchronously for a synchronous event/ operation with Task while taking a screenshot from the web browser/ web page using CefSharp
- ASP.net MVC 5 calling partial view thats in layout from Home controller
- JavaScript Failing in Partial View MVC
- A single view with two models in asp.net MVC 4
- cannot render asp.net mvc partial view
- Opening Google Maps inside a Partial View with JSON
- Using Serilog for Logging with Azure Table Storage in .NET Core MVC
- Adding Partial View with Switch Case in Controller
- setting page title when using strongly typed view data in asp.net mvc
- ASP.NET MVC data annotations with partial class doesn't work
- Nested If Statement to insert a link on picture with MVC Razor View
- MVC Partial View Will Not Load
- Updating only a partial view in asp.net mvc from another partial view
- Run javascript in a partial view with MVC5 C# and Razor
- If condition into Gridview Column design
- Determine action according to previous scene in unity
- Conditional element class outputs "class"
- listbox highlights the selecteditem even after coming back in mvvm windows phone app
- C# excel color text
- How to get the label text of a dynamically created user control
- How can I set properties on multiple clones in a generic list after instantiation
- Is there a way I can use something like a ? operator to check the value here and run either of these two without needing to use two if statements?
- How to get a string between 2 specific characters in C#
- LinkedListNode after add to LinkedList doesn't set next and previous fields
- The query can't be executed!ERROR: 22P04: extra data after last expected column
- Checkbox is only getting value from one checkbox. I need to get value for multiple checkboxes when selected
- Application hangs/freezes when setting RadGridView datasource
- Issue in Download file from google drive api in .net
- IndexOutOfRange unless I split the query into multiple queries
- C# Extensions working in console application but not in MVC web application. Am I missing something?
- Datetimepicker didn't recognized as valid datetime
- How to use Generic to simplify duplicated code in C#
- How to pass passwords as parameters in a method
- how to check if a string value exists in ReportParameter list c#