In the previous article, we have discussed insert update and delete data in MVC without Entity Framework ,In this post, We will do insert, update, and delete(Crud Operation) functionality in MVC using entity framework with ajax call jquery.
If also looking for the perform list, insert, update and delete in a single view in asp.net MVC then you have come to the right. Because in this post we will perform CRUD operation in a single view in MVC5 with the help of bootstrap modal popup.That means in this article we will use a bootstrap modal popup for performing the Crud operation.
We will cover the following point in this post
- CRUD operations in MVC using bootstrap modal popup
- Insert, update, delete i. e Crud operations using jquery ajax and modal
- Crud operation in MVC using the jquery data table
So Let’s start, step by step to learn how easily we can complete this task in any project. We will try to create a basic View where Users can see all the lists of records in a Table with add button for adding new database records, an edit button for updating existing database records, and delete links to delete any existing records with a confirmation alert box.
we have divided the entire article into the following parts.
- Creating New ASP.NET MVC Project for our task
- Creating Database Table for performing database operations
- Adding Connection EntityFramework in our project
- Creating Controller
- Adding Action Method in Controller
- Creating View from Action Method
- Configure RouteConfig.cs file
- Run your Project
Step 1- Create New ASP.NET MVC Project
Step 2- Creating Database Table for performing database operations
Let’s create the database table, for our crud operation. I have created a table called TblPatient with column Id, PatientName, PatientNumber, PatientEmail, Adress, and BloodGroup.below is the SQL Script of the table you can use for testing 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 3- Adding Connection EntityFramework in our project
Try the below step and follow the image 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.
It will create a model class for the table(representing the database table structure) which we will use as Model Class for the View.
Open TblPatient.cs you can see the model class
namespace CrudJqueryAjax.Models
{
using System;
using System.Collections.Generic;
public partial class TblPatient
{
public int Id { get; set; }
public string PatientName { get; set; }
public string PatientNumber { get; set; }
public string PatientEmail { get; set; }
public string Address { get; set; }
public string BloodGroup { get; set; }
}
}
Step 4. Creating Controller
Now let’s add a controller for performing database operation, Right-click on the Controller folder in the project and click on add an empty controller.I have created controller with Patient named.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace CrudJqueryAjax.Controllers
{
public class PatientController : Controller
{
// GET: Patient
public ActionResult Index()
{
return View();
}
}
}
Step 5. Adding Action Method in Controller
Now let’s write the logic in our controller, Open PatientController, and add the following action methods. Here, I am going to add five action methods to our controller
- For returning Index view which shows the list of patients- Index()
- Returning All Patient list in the database- GetPatientList()
- Returning single record from database By Id- GetPatientbyID()
- Action for creating the record in the database– AddPatient()
- For Updating records in the database– UpdatePatient()
- For deleting a record in the database– DeletePatient ()
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();
}
public JsonResult GetPatientList()
{
return Json(db.TblPatients.ToList(), JsonRequestBehavior.AllowGet);
}
public JsonResult AddPatient(TblPatient tblPatient)
{
string status = "success";
try
{
db.TblPatients.Add(tblPatient);
db.SaveChanges();
}
catch(Exception ex)
{
status = ex.Message;
}
return Json(status, JsonRequestBehavior.AllowGet);
}
public JsonResult GetPatientbyID(int PatientId)
{
try
{
var Patient = db.TblPatients.Where(a => a.Id == PatientId).FirstOrDefault();
return Json(Patient, JsonRequestBehavior.AllowGet);
}
catch(Exception ex)
{
return Json(null, 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);
}
}
}
SampleRestApiEntities is entity framwork DbContext object you can find name in web.config or context.cs file
6. Creating View from Action Method
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.
Now Open Index.cshtml and Copy paste the below code
Index.cshtml
@{
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">
<thead>
<tr>
<th>
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"></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-primary" id="btnUpdatepatient" style="display:none;" onclick="UpdatePatient();">Update 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">
//Load Data in Table when documents is ready
$(document).ready(function () {
BindpatientData();
});
//Bind Data function which is responoisble for loading all data from database
function BindpatientData() {
$.ajax({
url: "/Patient/GetPatientList",
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.PatientName + '</td>';
html += '<td>' + item.PatientNumber + '</td>';
html += '<td>' + item.PatientEmail + '</td>';
html += '<td>' + item.Address + '</td>';
html += '<td>' + item.BloodGroup + '</td>';
html += '<td><a href="#" onclick="return OpenEditPopup(' + item.Id + ')">Edit</a> | <a href="#" onclick="DelelePatient(' + item.Id + ')">Delete</a></td>';
html += '</tr>';
});
$('.tbody').html(html);
}
},
error: function (errormessage) {
alert(errormessage.responseText);
}
});
}
//************Adding Record in the database***********
function OpenAddPopup() {
//title text
$("#AddUpdateModelLabel").text("Add Patient")
//clear all input
ClearAllInput();
//open popup
$('#AddUpdateModel').modal('show');
//show add patient button and hide update button
$('#btnUpdatepatient').hide();
$('#btnAddpatient').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) {
//populate table with new record
BindpatientData();
//claer all input and hide model popup
ClearAllInput();
$('#AddUpdateModel').modal('hide');
},
error: function (errormessage) {
alert(errormessage.responseText);
}
});
}
function OpenEditPopup(PatienId) {
$("#AddUpdateModelLabel").text("Update Patient Detail")
ClearAllInput();
$.ajax({
url: "/Patient/GetPatientbyID?PatientId=" + PatienId,
typr: "GET",
contentType: "application/json;charset=UTF-8",
dataType: "json",
success: function (result) {
debugger;
$("#AddUpdateModelLabel").val("Update Patient Detail")
$('#hfpatientId').val(result.Id);
$('#txtPatientName').val(result.PatientName);
$('#txtPatientNumber').val(result.PatientNumber);
$('#txtPatientEmail').val(result.PatientEmail);
$('#txtAddress').val(result.Address);
$('#txtBloodGroup').val(result.BloodGroup);
$('#AddUpdateModel').modal('show');
$('#btnUpdatepatient').show();
$('#btnAddpatient').hide();
},
error: function (errormessage) {
alert(errormessage.responseText);
}
});
return false;
}
//function for updating Patient record
function UpdatePatient() {
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(),
};
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) {
BindpatientData();
ClearAllInput();
},
error: function (errormessage) {
alert(errormessage.responseText);
}
});
}
//function for deleting employee's record
function DelelePatient(ID) {
var ans = confirm("Are you sure you want to delete?");
if (ans) {
$.ajax({
url: "/Patient/DeletePatient?PatientId=" + ID,
type: "POST",
contentType: "application/json;charset=UTF-8",
dataType: "json",
success: function (result) {
BindpatientData();
},
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- Configure RouteConfig.cs file
Open RouteConfig.cs file inside App_Start folder and Change in controller name from Home=>Patient
because when we want to open the index view inside the Patient controller at the start of the application.
Now Build project and run in the browser
Why we should use Bootstrap in Mvc?
Bootstrap is a framework that we can usually use to quickly design any website. Bootstrap consists of pre-written CSS and JavaScript files in which many classes are pre-defined. These classes are used to make typography, HTML forms, pages responsive. Websites created in Bootstrap are more attractive and faster.
today, Almost all types of websites are being built in Bootstrap. If you are interested in web designing, this is a very important Javascript framework for any web designer. Which is used to design lightweight and mobile-friendly websites.
Bootstrap is the most popular HTML, CSS, and JavaScript framework for developing a responsive and mobile-friendly website. It is absolutely free to download and use. It is a front-end framework used for easy and fast web development.
Bootstrap was created by employees of the Twitter company Mark Otto and Jacob Thornton together with one of their teams. Here we would like to tell you for your information that in the beginning, they named it Twitter Blueprint because they wanted to use it as an internal tool for Twitter, and this was the main reason for developing it.
But later it was released on 19 August 2011 as an open-source project under the name of Bootstrap on GitHub. So that more people could use it, it became very popular as soon as it was seen and today developers from all over the world use it to design responsive websites.
If you use it through CDN, then it is very easy. But to use Bootstrap, you must have basic knowledge of HTML and CSS.
To use Bootstrap, you need to add the CDN of Bootstrap CSS, Javascript, and AJAX to the Html Code.
After that, all Ready Component (Grid, Container, Typography, Forms, Menubar) can be used by Copy Paste. If you want, you can also change their style with your Custom CSS Code.
How Bootstrap works?
When Web Designer designs a website with the help of Bootstrap, it does not need to do much coding. Bootstrap already contains lots of codes. Those are only reused on the Html Page.
Bootstrap contains a lot of Predefined CSS Classes that can be easily used on your page. Bootstrap works on the Grid System.
Which divides the entire page into equal columns and rows. Separate CSS Classes have been created for each Rows and Columns which can be used on the Web Page as required.
There are many benefits of using Bootstrap
This framework is very easy to use. If you know CSS and Html then you can use Bootstrap. And you can also change it. This also saves time, Code is already available in Bootstrap. So if you have to make some changes, then you do not need much coding.
Through this, you can easily create a responsive website. If your website is responsive then it adjusts itself according to the screen size in any platform or device. Can use Bootstrap for free.
If you want to change the in-built style already added to Bootstrap, then you can easily do it. You have to write the code of Bootstrap over by writing your CSS code with your CSS code.
The post Insert Update Delete Using Jquery Ajax and Modal Popup in Mvc 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#
- Couldn't able to Update the data in CRUD using AJAX and JQuery
- How to download the file using ASP.NET MVC Rest API call and jQuery Ajax
- How to manually store image in (database) table in Visual Studio 2012 and retrieve using jQuery Ajax in ASP.NET MVC
- I want to know how i can refresh a modal and display it after update data with Ajax call
- JSON data is returned as undefined after rendered using ajax JQuery in ASP.NET Core MVC app
- How to update existing rows and insert new rows using stored procedure?
- How tu update database using ajax and the PUT verb?
- Login form using JQuery ajax MVC
- MVC model update and create (multiple) at the same time using stored procedure
- how to upload image to server side using JQuery ajax and without library using asp.net webform?
- how to upload image to server side using JQuery ajax and without library using asp.net webform?
- C# ASP.NET MVC ajax Modal inside Modal hides onsuccess and failure only should onsuccess also refreshes first modal onsuccess
- C# ASP.NET MVC ajax Modal inside Modal hides onsuccess and failure only should onsuccess also refreshes first modal onsuccess
- Asp.Net Insert using bootstrap Modal Popup
- POST method to send RAW TEXT data and get HTML Response using Jquery AJAX Web Method and check with POSTMAN
- POST method to send RAW TEXT data and get HTML Response using Jquery AJAX Web Method and check with POSTMAN
- json function not call using jquery ajax in mvc
- using jquery each method and get data from table MVC Model
- Using same view for get, post and update request in MVC
- Insert Data Using jQuery Ajax in Asp.net C# [Database MySQL]
- How to get value of checkbox from checkboxlistFor using jquery ajax in MVC
- Update and Delete rows in GridView ASP.NET C# using stored procedure instead of using SqlDataSource
- PayUMoney Integration in MVC and calling using ajax
- PayUMoney Integration in MVC and calling using ajax
- Inserting value to database using Jquery and MVC
- How to use one function to Insert and update using the same button name
- How to use one function to Insert and update using the same button name
- C# MVC EntityState many to many delete and update
- How To Send Custom Header using Jquery Ajax and Retrieve the same header value in WCF Service using C#?
- mvc partial view autocomplete using modal jquery not displaying data in textboxfor
- How to use AdoAppender in log4net without config
- Check domain name of email Id for google oauth
- Gridview: Check only one Checkbox at a time
- Error parsing xml file with namespace
- Deep Linking for xamarin app without a website
- Data not saving in database using C# and Visual Studio
- .net-core Angular: HTTP Post Error 400 with Angular HTTPClient
- how to display Dictionary values to Data Grid View in window forms
- How can I update a Outlook PST file? C#
- How to get label name by labelId using GMAIL API
- Getting Jwt Token for current user logged in with AzureAd In c#
- Unity game crashes when closing Reward Based Video Ad
- How can I check changes to existing public api
- Unity Physics2D.Raycast having trouble with large 2D colliders
- page number in pdf file using iTextSharp 5.0.2.0
- Get free disk space in two loop
- Accessing SqlCeException on Windows Phone 8
- C# enter mathematical problem and solve it when user enter "="
- I am trying to write a xamarin forms application to simply take a photo and save the image,
- Windows Form Height Inconsistency