Introduction
In this article, we learn how to implement CRUD operations in an ASP.NET MVC application using Ajax requests, jQuery, and the DataTable Plugin. This article explores client-side validation, create, view, update, and delete on the Entity Model.
This article shows you step-by-step how to create an ASP.NET MVC CRUD Application. I attached the project source code in this article. First, you write all code in Visual Studio for better understanding, otherwise, use the source code download from this article and execute it in your Visual Studio.
Entity Framework
Entity Framework is an ORM (Object Relational Manager) Framework for . NET. It Increases the productivity of the developer. It can execute a necessary query for viewing or writing data in a database and executing it.
Let us start with the OUTPUT of our ASP.NET MVC web application. This is how it shows on a web browser.
Note. We execute CRUD Operations in ASP.NET MVC Applications, but you need to have basic knowledge about creating an ASP.NET MVC Application. If not familiar with ASP.NET MVC, then please explore the basics, It hardly takes an hour, then you can read this article.
Prerequisites
- Visual Studio 2013 or above. (Here I am using Visual Studio 2017).
- SQL Server 2012.
- MVC Version 5.0.0.0 or above.
- Check your MVC Version
- References -> Right-click on System. web.Mvc->properties.
- After clicking on Properties, it shows the properties window, check the MVC Version.
- I am using MVC 5.2.4.0 Version.
- If your MVC version is below 5.0.0.0, you have to update MVC.
Update MVC Command
Go to Tools -> NuGet Package Manager -> Package Manager Console.
After opening the console, write the following on the console.
PM> Install-Package Microsoft.AspNet.Mvc -Version 5.2.7
Bootstrap CSS: Follow the procedure to install it.
Right-click on Solution Explorer -> Manage NuGet Packages.
After the NuGet Package window, type Bootstrap in the search section.
jQuery version 1.12.4
jQuery UI => Install it from Right click on project -> Manage NuGet Packages -> type in Search online or Browse section jQuery UI.
Microsoft jQuery unobtrusive validation => Install it from Right click on project -> Manage NuGet Packages ->type in Search online or Browse section Microsoft jQuery unobtrusive validation.
Create Database
First, we create a database and table for performing CRUD Operations. This simply means performing a Select, Insert, Update, and Delete query on the Table.
I created MvcCRUDDB and a table named Student. Set the Primary key to StudentID. In the Table Property, set StudentID Identity to 1.
Let us start to Create an ASP.Net MVC Application for performing CRUD Operations.
Create a Project
Open Visual Studio and Go to File Menu -> New -> Project.
Left side Template select Visual C# -> web -> ASP.NET MVC Application -> Name it MvcCRUD.
(You can name your application the same name or any name you want).
Once you click on OK, you'll select the Empty project Template and Tick the MVC Checkbox.
After clicking on OK, the project structure will be shown below.
Now we install jQuery version 1.12.4, jQuery UI, Microsoft jQuery unobtrusive validation, and jQuery Validation.
All installation steps are shown in the above Prerequisites Section. Please follow all steps for a better application.
After installation, we need to download notify.min.js for Notification after the insert, update and delete operations.
Download Link: https://notifyjs.jpillora.com/
After the download, you import it into the Script Folder.
Right-click on Script Folder -> Existing Item -> Add -> Choose notify.min.js file in your system.
Create an Entity Data Model
Now we add the ADO.NET Entity Data Model to the Application. Follow the steps mentioned below.
Right-click on Model Folder -> Add ->New Item.
Select Data from Left Panel -> ADO.NET Entity Data Model -> Name it “DBModels” -> Click on add.
Select EF Designer from the database (If you use the earlier Visual Studio 2017 version, then Select Generate Data from Database)
Click on New Connection ->we need to provide a server name and Database name and click on ok.
Here we provide the Server name and Database Name for the New Database Connection.
Change the class name MvcCRUDDBEntities to DBModel.
Select the Entity Framework version. I usually prefer Entity Framework 6. x.
We need to select the database object of Table Student and click on the Finish Button.
Entity Model Show all Fields in the Student Table.
Entity Model shows all fields in the Student Table.
Controller
Let's add a new Controller to get data from the database using the Entity Data Model.
Follow the Steps
Right-click on Controller -> add -> controller.
Select MVC5 Controller Empty -> click on add -> Name this controller StudentController.
Now open StudentController.
In this Controller, we need to Four ActionResult Methods.
Get Operation
This ActionResult GetData Method is used tp return all the data from the student table to View as a generic list connection.
public ActionResult GetData()
{
using (DBModel db = new DBModel())
{
List<Student> studentList = db.Students.ToList<Student>();
return Json(new { data = studentList }, JsonRequestBehavior.AllowGet);
}
}
Insert and Update Operation
We create ActionResult StoreOrEdit() for the insert and update operations. In this ActionResult Method, the received Student entity is inserted into the Student Table, and the updated Student entity with generated StudentID is returned back to view.
For updating the record, in this ActionResult Method, the Student entity is received as a parameter. The ID of the Student entity is used to reference the Student Record in the Student Table. It updates the student table.
We used the [HttpGet] and [HttpPost] Methods for Posting client Data or Form data to the Server.
[HttpGet]
public ActionResult StoreOrEdit(int id = 0)
{
if (id == 0)
return View(new Student());
else
{
using (DBModel db = new DBModel())
{
return View(db.Students.Where(x => x.StudentID == id).FirstOrDefault<Student>());
}
}
}
[HttpPost]
public ActionResult StoreOrEdit(Student studentob)
{
using (DBModel db = new DBModel())
{
if (studentob.StudentID == 0)
{
db.Students.Add(studentob);
db.SaveChanges();
return Json(new { success = true, message = "Saved Successfully" }, JsonRequestBehavior.AllowGet);
}
else
{
db.Entry(studentob).State = EntityState.Modified;
db.SaveChanges();
return Json(new { success = true, message = "Updated Successfully" }, JsonRequestBehavior.AllowGet);
}
}
}
Delete Operation
We need to create ActionResult Delete, the StudentID received as a parameter. This Parameter StudentID passed for deleting Data.
[HttpPost]
public ActionResult Delete(int id)
{
using (DBModel db = new DBModel())
{
Student emp = db.Students.Where(x => x.StudentID == id).FirstOrDefault<Student>();
db.Students.Remove(emp);
db.SaveChanges();
return Json(new { success = true, message = "Deleted Successfully" }, JsonRequestBehavior.AllowGet);
}
}
Route Data
Once we write code in the controller, then We Set the Student Controller as DefaultController.
Go to the App_start folder then click on RouteConfig.cs.
It shows you the routes.MapRoute. Set the StudentController to Default controller by replacing “Home” with” Student”.
View
We need to Create two Views for Displaying Data and the Insert/Edit Operation.
Go to StudentController.cs. Click on Index Function -> Right click -> Add View.
Keep the view name as it is; Index -> click on add.
Index.cshtml View consists of the following code.
@{
ViewBag.Title = "Student List";
}
<h2>Student Record</h2>
<a class="btn btn-primary" style="margin-bottom:10px" onclick="PopupForm('@Url.Action("StoreOrEdit","Student")')"><i class="fa fa-plus"></i>Add New</a>
<table id="StudentTable" class="table table-striped table-bordered" style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>Department</th>
<th>Semester</th>
<th>Age</th>
<th>Fees</th>
<th></th>
</tr>
</thead>
</table>
<link href="https://cdn.datatables.net/1.10.21/css/dataTables.bootstrap.min.css" rel="stylesheet" />
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
@section scripts{
<script src="//cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/dataTables.bootstrap.min.js"></script>
<script>
var Popup, dataTable;
$(document).ready(function () {
dataTable = $("#StudentTable").DataTable({
"ajax": {
"url": "/Student/GetData",
"type": "GET",
"datatype": "json"
},
"columns": [
{ "data": "Name" },
{ "data": "Department" },
{ "data": "Semester" },
{ "data": "Age" },
{ "data": "Fees" },
{
"data": "StudentID", "render": function (data) {
return "<a class='btn btn-default btn-sm' onclick=PopupForm('@Url.Action("StoreOrEdit","Student")/" + data + "')><i class='fa fa-pencil'></i>Edit</a> <a class='btn btn-danger btn-sm' style='margin-left:5px' onclick=Delete(" + data + ")><i class='fa fa-trash'></i>Delete</a>";
},
"orderable": false,
"searchable": false,
"width": "150px"
}
],
"language": {
"emptyTable": "No data found please click on <b>Add New </b> Button"
}
});
});
function PopupForm(url) {
var formDiv = $('<div/>');
$.get(url)
.done(function (response) {
formDiv.html(response);
Popup = formDiv.dialog({
autoOpen: true,
resizable: false,
title: 'Fill Student Details',
height: 500,
width: 700,
close: function () {
Popup.dialog('destroy').remove();
}
});
});
}
function SubmitForm(form) {
$.validator.unobtrusive.parse(form);
if ($(form).valid()) {
$.ajax({
type: "POST",
url: form.action,
data: $(form).serialize(),
success: function (data) {
if (data.success) {
Popup.dialog('close');
dataTable.ajax.reload();
$.notify(data.message, {
globalPosition: "top center",
className: "success"
})
}
}
});
}
return false;
}
function Delete(id) {
if (confirm('Are you sure to Delete this record ?')) {
$.ajax({
type: "POST",
url: '@Url.Action("Delete","Student")/' + id,
success: function (data) {
if (data.success) {
dataTable.ajax.reload();
$.notify(data.message, {
globalPosition: "top center",
className: "success"
})
}
}
});
}
}
</script>
}
After adding the index view -> Go to View Folder -> Shared Folder -> Open _Layout. cshtml.
_Layout. cshtml consists of the following code.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - My ASP.NET Application</title>
<link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
<link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="~/Content/themes/base/jquery-ui.min.css" rel="stylesheet" />
</head>
<body>
<div class="container body-content">
@RenderBody()
<hr />
<footer>
<p>ASP.Net MVC CRUD Application using jQuery Ajax with Entity Framework</p>
</footer>
</div>
<script src="~/Scripts/jquery-1.12.4.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="~/Scripts/jquery-ui-1.12.1.min.js"></script>
<script src="~/Scripts/notify.min.js"></script>
@RenderSection("scripts", required: false)
</body>
</html>
After implementing _layout. cshtml. We need to create a view for StoreOrEdit.
Go to Student Controller -> Right-click on StoreOrEdit Section and add view.
Keep the View Name as it is and uncheck use a layout page and click on Add.
Store or edit view, which contains the following code.
@model MvcCRUD.Models.Student
@{
Layout = null;
}
@using (Html.BeginForm("StoreOrEdit", "Student", FormMethod.Post, new { onsubmit = "return SubmitForm(this)" }))
{
@Html.HiddenFor(model => model.StudentID)
<div class="form-group">
@Html.LabelFor(model => model.Name, new { @class = "control-label" })
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="form-group">
@Html.LabelFor(model => model.Department, new { @class = "control-label" })
@Html.EditorFor(model => model.Department, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Department)
</div>
<div class="form-group">
@Html.LabelFor(model => model.Semester, new { @class = "control-label" })
@Html.EditorFor(model => model.Semester, new { htmlAttributes = new { @class = "form-control" } })
</div>
<div class="form-group">
@Html.LabelFor(model => model.Age, new { @class = "control-label" })
@Html.EditorFor(model => model.Age, new { htmlAttributes = new { @class = "form-control" } })
</div>
<div class="form-group">
@Html.LabelFor(model => model.Fees, new { @class = "control-label" })
<div class="input-group">
<span class="input-group-addon">
₹
</span>
@Html.EditorFor(model => model.Fees, new { htmlAttributes = new { @class = "form-control" } })
</div>
</div>
<div class="form-group">
<input type="submit" value="Submit" class="btn btn-success" />
<input type="reset" value="Reset" class="btn btn-warning" />
</div>
}
If site.css is not available in the Content folder, then right-click on Content folder->add->click on stylesheet->name it Site.css.
Site.css consists of the following code. It's used to show error messages on the screen in client-side validation.
.field-validation-error {
color: #e80c4d;
font-weight: bold;
}
input.input-validation-error {
border: 1px solid #e80c4d;
}
Client-Side Validation
Expand Model Folder->DBModels.edmx->DBModels.tt->Open Student. cs file
It consists of the following code.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace MvcCRUD.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public partial class Student
{
public int StudentID { get; set; }
[Required(ErrorMessage = "This Field is Required")]
public string Name { get; set; }
[Required(ErrorMessage = "This Field is Required")]
public string Department { get; set; }
public string Semester { get; set; }
public Nullable<int> Age { get; set; }
public Nullable<int> Fees { get; set; }
}
}
StudentController.cs consists of the following code.
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcCRUD.Models;
namespace MvcCRUD.Controllers
{
public class StudentController : Controller
{
// GET: Student
public ActionResult Index()
{
return View();
}
//Fetch Data From Database to show in Datatable
public ActionResult GetData()
{
using (DBModel db = new DBModel())
{
List<Student> studentList = db.Students.ToList<Student>();
return Json(new { data = studentList }, JsonRequestBehavior.AllowGet);
}
}
//Create Method for Insert and Update
[HttpGet]
public ActionResult StoreOrEdit(int id = 0)
{
if (id == 0)
return View(new Student());
else
{
using (DBModel db = new DBModel())
{
return View(db.Students.Where(x => x.StudentID == id).FirstOrDefault<Student>());
}
}
}
[HttpPost]
public ActionResult StoreOrEdit(Student studentob)
{
using (DBModel db = new DBModel())
{
if (studentob.StudentID == 0)
{
db.Students.Add(studentob);
db.SaveChanges();
return Json(new { success = true, message = "Saved Successfully" }, JsonRequestBehavior.AllowGet);
}
else
{
db.Entry(studentob).State = EntityState.Modified;
db.SaveChanges();
return Json(new { success = true, message = "Updated Successfully" }, JsonRequestBehavior.AllowGet);
}
}
}
[HttpPost]
public ActionResult Delete(int id)
{
using (DBModel db = new DBModel())
{
Student emp = db.Students.Where(x => x.StudentID == id).FirstOrDefault<Student>();
db.Students.Remove(emp);
db.SaveChanges();
return Json(new { success = true, message = "Deleted Successfully" }, JsonRequestBehavior.AllowGet);
}
}
}
}
Now our web application is ready to learn. Run the application and click on the Run Button or Press F5.
Here is the Output. There is no data in the database, that's why it shows No Data Found.
Insert Operation Output
Click on the Add New Button, after that it shows a Popup Form.
Client-Side Validation Output.
Output
Now you go to SQL Server and check the student table data. It shows you the Inserted data.
If your popup form not working, it means you did not download the plugin. Download all plugins mentioned in the Prerequisites.
Now you have implemented CRUD operations in your project.
Conclusion
Finally, we completed performing CRUD Operations in ASP.NET MVC using Entity Framework with the help of jQuery, Ajax Request, and DataTable.
In this application, we implemented the DataTable Plugin, Bootstrap, jQuery, and Clientside Validation. It showed a popup for inserting data and updating data.
Download the source code file of the CRUD Web Application in ASP.NET MVC. The source code is attached to this article.
I hope this article was helpful to you for developing a CRUD Application in ASP.NET MVC.