Here we’ll discuss how to use jQuery Ajax CRUD Operations in ASP.NET Core MVC with Bootstrap Modal. To demonstrate this, we implement operations insert, update, delete and retrieve with online bank transaction details. With jQuery Ajax we can make request to controller action methods without reloading, these types of user interface is usually implemented in most of the enterprise applications out there.
Sub-topics discussed :
- Open an URL in a modal popup dialog.
- Form post using jQuery Ajax.
- Implement MVC CRUD operations with jQuery Ajax.
- Loading spinner in ASP.NET Core.
- NoDirectAccess attribute.
Create ASP.NET Core MVC Project
In Visual Studio 2019, Go to File > New > Project (Ctrl + Shift + N).
From New Project window, Select Asp.Net Core Web Application.
Once you provide the project name and location. Select Web Application(Model-View-Controller) and uncheck HTTPS Configuration. Above steps will create a brand new ASP.NET Core MVC project.
Let’s create a database for this application using Entity Framework Core. For that we’ve to install corresponding NuGet Packages. Right click on Project Name from Solution Explorer, Click on Manage NuGet Packages, From Browse Tab– install following 3 packages. Select package version same as that of your ASP.NET Core to avoid version conflict with framework.
Now let’s define DB model class file (/Models/TransactionModel.cs).
Here we’ve defined model properties for the transaction with proper validation. Now let’s define DbContext for EF Core.
Now let’s inject this DbContext class in Startup.cs.
Now add connection string – DevConnection, in appsettings.json.
Now let’s execute migration command one by one.
After the successful migration, you could check the physical DB whether it is created as per the model or not.
Add MVC Controller with CRUD Action Methods
Now let’s add an MVC Controller, with Action Methods for CRUD Operations – Insert, Update, Delete and Retrieve. For that right-click on Controllers folder, Add > Controller. and then select MVC Controller with views, using Entity Framework. Fill up the window with corresponding details.
If you face the following error while creating the controller. you should try again after installing the NuGet Package – Microsoft.VisualStudio.Web.CodeGeneration.Utils.
Inside the controller, you could see action method for the crud operations for both GET and POST request.
Let’s Start Designing the App
First of all, I want to add references for Google Font – Roboto and Font Awesome Icon in the main layout – _Layout.cshtml.
Now let me update the global stylesheet (wwwroot/css/site.css) with all required css rule for the entire application.
You could access the newly created controller with this route – /Transaction/[action_name]. You can configure this controller as default route in Startup.cs.
Inside the controller index action, we retrieve all of the records from the table. now let’s update the index view from which we’ve to do all other operations with the help jQuery Ajax.
Inside this index view, we’ve done some major changes. First of all added the validation scripts in Scripts section. By default in index.html, we had a table for listing transaction records. we’ve to move that into a new partial view _ViewAll. We’ve to re-render the table after each operation like insert, update and delete. So it’s better to move the table into a separate partial view for jQuery Ajax Get request later. Create the file _ViewAll.cshtml in /Views/Transaction folder as shown below.
Implement Insert and Update Operation
In transaction controller, you could see Add or Edit action method with their views. In this project, we will combine these two action methods and their views to one called – AddOrEdit. for AddOrEdit view, you just need to make few changes in existing view Edit.cshtml. First of all, rename the file to AddOrEdit.cshtml and update the file as shown below.
There are some re-arrangement for input controls, other than that, mainly we’ve changed the form post action method to AddOrEdit, and asp-route-id is set to PK property – TransactionId. Because this form should be submitted to post action method – AddOrEdit with the parameter id for TransactionId. In this view, you could see an additional hidden property – Date. Because it’s value is passed from code ( not from user interface ) with the date at which transaction is made.
Now let’s define the corresponding GET and POST action method – AddOrEdit. so add following action methods in TransactionController.
Here we have GET and POST action method for AddOrEdit. Inside these action methods, we just combined Existing Create and Edit action methods. To know whether we’ve add insert or update operation, we can check id (TransactionId) parameter. if its value is zero then we’ve an insert operation otherwise it is an update operation.
From GET action method, it returns the view AddOrEdit, that we’ve just created. Inside POST action method, we’ve done the Insert/ Update operation based on the id. The request into this POST action method will be made using jQuery Ajax. so the action method must return a JSON Object. To refresh the list of records (transactions), _ViewAll action method is passed in html property. In order to convert a view into HTML string, we’ve defined a function inside a new C# file – Helper.cs as shown below.
How to do jQuery Ajax Form Post
- showInPopup() – to open a url in modal popup
- jQueryAjaxPost() – to submit a form using jQuery Ajax.
Now let’s define these functions in wwwroot/js/site.js.
To open a request-response in showInPopup method, we’ve used bootstrap modal, so let’s add its Html elements in _Layout.cshtml as shown below, just before the footer.
Inside showInPopup method, we will make the GET request to the given url, and request-response is saved inside modal-body div. we open the model with the function modal function. we’ve called this function for adding new transactions in table header button and also in edit/ update button for a given record row, to open the form by populating the record details in input controls.
In jQueryAjaxPost, we make the Ajax Post request to the form action URL. If validation is failed the same form with validation error messages will be replaced in current modal popup, If validation is succeeded, then html string for the table is replaced in place of current table div. finally to prevent from the default form submission, we have returned false from the function. we’ve called this function for insert and update operation. The modal popup with the form looks like this.
Delete a Record with jQuery Ajax
Now let’s delete a record with the help of jQuery Ajax, we’ve already added the delete button for each table row. Actually it is a form submit button. Its always recommended to implement delete operation with a post request. Here we called DeleteConfirmed action method (URL – Transaction/Delete). Now we’ve to update the corresponding delete post action method as shown below.
Now let’s add corresponding jQuery Ajax post method- jQueryAjaxDelete in wwwroot/js/site.js.
After the delete operation, Html from _ViewAll is replaced in place of the table. we’ve completed with implementing jQuery Ajax CRUD operations in ASP.NET Core MVC. As of now our application looks like this.
Add Loading Spinner
Now let’s look how to add loading spinner, while waiting for request-response from the server. For that you can add following div in main layout _Layout.cshtml, just above the footer.
We’ve already added it’s corresponding CSS styles with animation in site.css. using jQuery we’ve to show and hide this spinner during Ajax request-response as shown below. just add following jQuery load event in wwwroot/js/site.js.
Prevent Direct Access to Action Methods in ASP.NET Core
In this application, we accessed the AddOrEdit GET request only through jQuery Ajax. you can also access the GET action method – AddOrEdit with URL – /Transaction/AddOrEdit. But it would be a plan Html and not plesant. If there is any such action methods only defined for jQuery Ajax Request we’ve to block the direct access to them. For that, we can create a NoDirectAccess attribute in Helper.cs file.
Now you just need to add this attribute to GET action method – AddOrEdit as shown below.
Step By Step Video Tutorial
In our YouTube channel, we have discussed the same topic in following video.