In this article, we’ll implement CRUD operations in Asp.Net MVC with jQuery Ajax Using JSON and Entity Framework.
You can download this project source code from here : https://goo.gl/kPCjWm
Create Asp.Net MVC Project
First of all, let’s create an Asp.net MVC Project, Open your Visual Studio.
Go to File > New > Project ( Ctrl+Shift+N).
Then select MVC Template.
Now we have a brand new Asp.Net MVC Application. Before continuing with this project, let me create SQL Server database for this application.
Create a Database
I use Management Studio to create and manage SQL Server DB. A database with name ‘jQueryAjaxDB’ is created.
In this application, we’ll deal with details of employees. So an employee table is created using following SQL Script.
That is enough for database part. Back to Visual Studio, then add ADO.NET Entity Data Model for the database.
Add Entity Model for Database
In-order to add Entity Model inside Models folder. Right click on Models Folder, Add > New Item. I have named this Entity Model as DBModels.
Select Generate from database.
In Entity Data Model Wizard, Click On New Connection.
Provide SQL Server instance details and then select the DB – jQueryAjaxDB.
As per previous Entity Data Model Wizard window, we’ll save DB Connection string in WebConfig as DBModel. After creating this Entity Model, there will be a class with this name ( DBModel ). We’ll create an object of this class in-order to interact with database.
From Entity Data Model Wizard, you will get following window, select tables that we want to add inside the Entity Model.
Click on Finish. Diagrammatic Representation of newly created EF Model looks like this.
Inside this DBModels.edmx, you can see a DBModels.Context.cs file for DBModel Class. we’ll create an object of this class to work with database.
DBModels.tt > Employee.cs contains Employee Class, which contains properties corresponding to SQL Table columns, So Employee class will be model class for this MVC application..
Add MVC Controller
Right click on Controllers folder, Add > Controller. Select Empty MVC Template, then name your controller as EmployeeController. Currently this Employee controller has one action method Index. In-order to implement CRUD Operations, we’ll add following action methods in Employee Controller.
- Index – Display other action method views using tab controller. Like Home/ Dashboard for the controller.
- ViewAll – Return an HTML table, to list records from Employee table.
- HttpGet AddOrEdit – Should return a view containing form for Insert and Update Operation. If the method parameter id is zero, we’ll return form for Insert Operation otherwise It will be form to update an employee with EmployeeID is equal to given id parameter.
- HttpPost AddOrEdit – Form returned from HttpGet AddOrEdit will be posted to this action method. Inside this action method, Insert Or Update Operation will be done based on EmployeeId inside emp object.
- HttpPost Delete – Used to Delete an employee record with given EmployeeID through id parameter.
I want to make the Employee controller as default controller, for that you can update RouteConfig as follows.
Let’s Start the Design
By default, there is a global style sheet – Site.css inside Content folder. Added some additional CSS rules inside the file.
For an MVC Application, default layout page will be _Layout.cshtml (Inside /Views/Shared Folder). Made some changes to default nav bar and footer. Finally _Layout.cshtml file looks like this.
Later we’ll show and hide during jQuery Ajax server side request.
By defualt, jquery and boostrap bundles are added to this layout. All of these bundles are defined inside App_Start/BundleConfig.cs file.
Index Action Method
Inside Employee controller, we have an action method Index as follows
Let’s add a view for this action method, right click inside the action method then select Add View. view name will be Index with Empty Template then check ‘Use a layout page’, Click on Add. Inside this view file we have used following code.
By default, for this view _Layout.cshtml will be the layout page. Here we have used a Bootstrap tab control with two tabs. One for listing records from Employee table. Inside the second tab, we’ll show the form for Insert or Update operation.
Then we have jQuery Datatable stylesheet and script file reference. Script codes are added inside the scripts section, which is defined inside the layout page. Along with this script file, we have added jqueryval bundle for client side validation.
Let’s Update Employee Class
I have updated Employee model class, which was automatically created inside Entity Model.
Required attribute is added to Name property with an error message. An Extra Property ImageUpload of the type HttpPostedFileBase is added. It will use this for Image Upload.
Inside the constructor, we initialized ImagePath property with a default Image path. we have add an image default.png inside AppFiles > Images Folder ( these two folders are added to the solution explorer).
List Records from Employee Table
Inside the first Bootstrap tab, we’ll list records from Employee table using an HTML table with a help of ViewAll action method.
Here GetAllEmployee() function returns list of employee from Employee table. Now let’s create a view for this ViewAll action method – ViewAll.cshtml.
For this view, we have an IEnumerable of Employee as Model. No layout page used for this view. Employee records are listed using HTML table with id – employeeTable. Inside the last column we have added buttons for Edit and Delete Operation. Onclick events are added to both of them – Edit() and Delete(). When we click on Edit, we call HttpGet AddOrEdit action method with an employeeID, from that action method we will return a form to update the corresponding employee record. We show this form inside the second tab of tab control. Both these functions are discussed in later parts of this article.
We have added jQuery Datatable to add more functionalities to this HTML table. An example for jQuery Datatable can be found here. In-order to activate this plugin for the table, we have defined a new function inside index view as follows.
We call this activatejQueryTable() from document ready event.
Implement Insert and Update Operation
Now let’s return a form for Insert and Update Operation with HttpGet AddOrEdit.
For Insert Form( id will be 0), we will return a view with fresh Employee object. For Update form( id ≠ 0 ), method returns a view with an object for given EmployeeId.
Now let’s create a view for this AddOrEdit action method. You can use following Razor code in AddOrEdit.cshtml.
Inside this view, we have a lot of things to discuss. Model for this view is Employee class from ADO.NET Entity Data Model. We don’t need a layout page for this, that’s why we set Layout as null.
We created the form with the using statement as follows
First two parameters of BeginForm() method tells where do we want to post the form after submission. Then we specified two attributes.
- Since this form contains file upload we set enctype to ‘multipart/form-data’.
- Then we’ve data attribute data-resetUrl, inside this we have an Url to reset this form controls to it’s initial state. Here we written underscore instead of hyphen ( data_restUrl instead of data-restUrl ), after rendering it will convert to hyphen format.
jQuery Ajax Operations With JSON
Finally we wired up a Submit event to jQueryAjaxPost() function. We’ll define this function inside our script file Scripts.js.
We have designed this form using Bootstrap as a series label-text pair. For text boxes we have applied bootstrap class form-control like this.
In-order to work this way, you must have MVC version greater than or equal to MVC 5.1. To update your existing project, Select the project from Solution Explorer. Go to Tools > Library package Manager > Package Manager Console. Then use following NuGet Command.
Then we have an img controll with id ‘imagePreview’ to show preview of selected image for upload. Then we have a file up-loader as follows
name of this control must match with HttpFileBase property ImageUpload from model class Employee. accept attribute indicate allowed image extensions for upload. Finally we have wired up onchange event to ShowImagePreview() function. To display preview of selected image for upload.
Now we have to define these script functions for – ShowImagePreview() and jQueryAjaxPost() inside Scripts.js file as follows.
ShowImagePreview() function is straight forward, it has two parameter – file up-loader and image for preview. if there is an image for upload it will be shown inside preview img control.
refreshAddNewTab() – It will replace the form with fresh form returned from resetUrl. In this case, it will be an URL for HttpGet AddOrEdit action method. Inside the function we made a jQuery Ajax call to MVC action method. If showViewTab parameter is true, first ‘ViewAll’ tab will be activated.
jQueryAjaxPost() – This is the meat of this article – Asp.Net MVC With jQuery Ajax. Here we make the first jQuery ajax post request to mvc action method AddOrEdit.
First of all we manually called for client side validation with following line.
We made Name property as mandatory field for the form, If validation fails, validation error will shown.
If the form is valid, we will go for jQuery Ajax Post Operation. After Insert / Update Operation, HttpPost action method AddOrEdit will return a JSON data. returned JSON object contains success property to indicate whether server side operation is success or not, along with that it has message property to return notification message contains message or exception message in case of an error.
After Insert/ Update Operation, It will return HTML of ViewAll action method with updated employee list inside JSON property html. we replace this html inside first Bootstrap tab View All. Then replace the form with fresh AddOrEdit form with data-restUrl attribute of the form and we will make first tab as active. After that we have shown the notifyjs message popup. Then we called activatejQueryTable() function to convert HTML table to jQuery Datatable, before that we made check whether there is a function with this name or not. These script functions are written for general purpose, There might be other MVC controller which may not need this function call.In that case you can avoid the function activatejQueryTable() from Index view.
Following lines are special for forms with file upload.
Server Side Operation – Insert and Update Operation
Above form will be submitted to HttpPost action method, where we need to implement Insert or Update operation as follows.
First of all, If there is an image for upload. we will a custom file by appending formatted datetime to original filename in-order to avoid duplicate file name inside Images folder, then save the image inside Images folder. After that we will do Insert or Update Operation based on EmployeeID value.
Inside the form we kept an hidden field for EmployeeID and ImagePath. This ImagePath contains previous image path before update operation, if there is not image selected for upload (during update operation) we can use that.
Finally we returns a JSON data, for html property we called another function RenderRazorViewToString(), it will return HTML string of a view with given model. in-order to define the function I have added new C# class file – GlobaalClass, inside that we defined the function as follows.
How to Update an Employee Record
It will populate the form for update operation inside the second tab. Upon form submission it will go to HttpPost action method and It will update the record as we discussed.
Delete an Employee Record
In-order Delete an Employee, you can click on delete button inside ViewAll view. It will call script function Delete() to HttpPost Delete action method. Here is the script function Delete().
Inside success function, we update the view all table with updated employee records. then shown NotifyJs notification and activated jQueryDataTable for updated Employee list.
Here is the HttpPost Delete action method.
Inside this Asp.Net MVC With jQuery Ajax Application, we implemented CRUD Operations – Insert Update and Delete.
Loading Spinner / Image in Asp.Net MVC
Finally I want to show the loading spinner div from _Layout page.
We already added loading to this using CSS style sheet Site.css. Using jQuery we will show and hide this div during jQuery Ajax Operations. for that we following code inside Scripts.js with document ready event.
Application Demo :
Step by Step Video Tutorial
That’s all, let me know your comments and feedback. Happy Coding :)