Google News
logo
Jquery Ajax Crud In Asp.Net Core Mvc With Modal Popup
Meravath Raju

Publisher : Meravath Raju



Excerpt : If you come from a programming background, you're probably familiar with the terms jQuery, Ajax, and Asp.net. But don't worry if you aren't because we'll cover it today. We'll go over how to use Bootstrap Modal with jQuery Ajax for ASP.NET Core MVC CRUD Operations.
Table of contents:

● Introduction
● Create an ASP.NET Core MVC project in Visual Studio
● Make database
● Create an MVC Controller that has CRUD Action Methods
● the app design
● In ASP.NET MVC, how do you do jQuery Ajax Form Post?
● Using jQuery Ajax, you can delete a record.
● Conclusion
 
Introduction:

When you use jQuery Ajax to implement CRUD operations, the whole webpage is loaded up for each user request. We can make HTTP requests to controller action methods using jQuery Ajax without resetting the entire page, similar to a single-page application.

Similar to a single-page application built with front-end frameworks such as Angular or React, this provides better performance and lower bandwidth usage. The project was created to demonstrate CRUD operations (insert, update, delete, and retrieve). Will deal with the specifics of a typical bank transaction.
Now step by step, we will be discussing the jquery ajax in asp.net with the use of a modal popup.

Create an ASP.NET Core MVC project in Visual Studio.
Jquery Ajax Crud ASP

Visual Studio 2019 is a new version of Visual Studio. (Ctrl + Shift + N) Go to File > New > Project.

Select Asp.Net Core Web Application from the new project window.

Once you've given the project a name and a location, you're ready to go. Uncheck HTTPS Configuration and select Web Application(Model-View-Controller). The steps above will generate a new ASP.NET Core MVC project.  For Candidates who want to advance their career, jQuery training is the best option



Make a database

Let's use Entity Framework Core to create a database for this application. To do so, we'll need to install the necessary NuGet packages. From the solution explorer, right-click on the project, select Manage NuGet Packages, and then install the following three packages from the Browse tab.



Now we'll create a DB model class file called /Models/TransactionModel.cs.




For the transaction, we've characterised model properties with proper verification. Let's create the DbContext class for EF Core now.



This class determines what should be in the physical database after migration. We decided to add a corresponding DbSet property – Transactions to the above model to create a table – Transactions. We'll be creating new instances of the DbContext class with ASP.NET Core dependency injection, which we can do in the Startup.cs file as shown below.



The value of the function Object() { [native code] } parameter is required when creating the class instance. The database provider (SQL Server, MySQL, Oracle, etc.) and its connection string are required by the context class function Object() { [native code] } parameter DbContextOptions. Let's now add the DevConnection connection string to appsettings.json.



Let's run the following migration commands one by one to create the actual physical database based on the connection string.


After the transfer is complete, you can check to see if the new database was created according to our DB model.
Create an MVC Controller that has CRUD Action Methods :

Let's now add an MVC controller with CRUD-related action methods. To do so, right-click on the Controllers folder and select Add > Controller from the menu. Then choose 'Entity Framework MVC Controller with Views'. Fill in the blanks in the window with the relevant information.

If you encounter the below error while creating the controller, please contact us. After installing the Microsoft.VisualStudio.Web.CodeGeneration.Utils NuGet Package, try again.

You had seen action methods for the crud operations for both GET and POST requests inside the controller. When a request is made to this controller, the ASP.NET Core framework automatically creates an instance of it. The value for the function Object() { [native code] } parameter TransactionDbContext is managed to pass from the dependency injection at the very same time.

Let's get started on the app design :

First and foremost, we want to reference the Google Font Roboto and Font Awesome Icon style sheets in the main layout – _Layout.cshtml
Let me now update the global stylesheet (wwwroot/css/site.css) with all of the application's required CSS rules.

IMAGE: https://www.codaffection.com/asp-net-core-article/jquery-ajax-crud-in-asp-net-core-mvc/  (image code 1)

An URL in the format /Transaction/[action name] could be used to access the newly created controller action methods. This controller can be set as the default route in Startup.cs.

We get all of the records from the transactions table using the controller index action. Let's update the corresponding index view, from which we'll use jQuery Ajax to perform all other operations.

We've made some significant changes to this index view. First, in the Scripts section, we added the validation scripts. We had a table for listing transaction records by default in index.html. We'll put that in a new partial view called _ViewAll. After each operation, such as insert, update, and delete, we must re-render the table. As a result, it's preferable to separate the table into a separate partial view for later jQuery Ajax Get requests. As shown below, create the file _ViewAll.cshtml in the /Views/Transaction folder.

IMAGE : https://www.codaffection.com/asp-net-core-article/jquery-ajax-crud-in-asp-net-core-mvc/  (image code 1)

Besides that, we've altered the form post action method to AddOrEdit and set asp-route-id to PK property – TransactionId. An additional hidden property – Date – can be seen in this view. Which is the transactional data?
 
In TransactionController, define the corresponding GET and POST action methods AddOrEdit.

IMAGE : https://www.codaffection.com/asp-net-core-article/jquery-ajax-crud-in-asp-net-core-mvc/

We simply combined existing Create and Edit action methods within these action methods. We can check the id(TransactionId) parameter to see if we have an insert or update operation. If its value is zero, we're dealing with an insert operation; otherwise, we're dealing with an update operation.

If the id parameter is zero, a new transaction form will be returned; otherwise, the corresponding transaction details will be populated in the returned form. Insert/Update operations will be performed within the POST action method based on the id. Because jQuery Ajax will be used to make the request to this POST action method, the action method must return a JSON object. The _ViewAll action method is passed in the html property and can be used to replace the transaction list. We've defined a function in a new C# file called Helper.cs to convert a view into an HTML string, as shown below.

In ASP.NET MVC, how do you do jQuery Ajax Form Post?

We obligated two JavaScript functions to the AddOrEdit action method.
 
showInPopup() is a Bootstrap modal popup function that opens the response from a GET request.

jQueryAjaxPost() uses jQuery Ajax to submit a form.

Now, in wwwroot/js/site.js, let's define these functions.

https://www.codaffection.com/asp-net-core-article/jquery-ajax-crud-in-asp-net-core-mvc/

We have been using bootstrap modal to open a request-response with showInPopup, so let's add its HTML elements to _Layout.cshtml just before the footer, as shown below.

We'll make a GET request to the given URL inside the showInPopup method, and the request-response will be saved inside modal-bodydiv. The modal function was used to open the Bootstrap model. This showInPopup function is used to add new transactions from the table header button, as well as to show specific transaction details for update operations from the edit/ update button.

We must perform the following operations in the jQueryAjaxPost function.
Form Validation: Before submitting the form, the form controls must be validated. If validation fails, the same form with validation error messages/indications will be displayed.

Validation of the data is guaranteed if the form is submitted successfully. Now we can make a jQuery Ajax post request to the URL of the form action. If the request is successful, the table's returned html response string is substituted for the current table div. Finally, we returned false to prevent the form from being submitted by default.

This function performs both insert and updates operations. After all, this is how the modal popup will appear.


Using jQuery Ajax, you can delete a record: 

Let's use jQuery Ajax to delete a record; we've now also decided to add the delete button to each table row. It's actually a form with a submit button on it. Using a post request to implement a delete operation is always recommended. The DeleteConfirmedaction method (URL – Transaction/Delete) was used here. Now, as shown below, we must update the corresponding delete post-action method.

https://www.codaffection.com/asp-net-core-article/jquery-ajax-crud-in-asp-net-core-mvc/
Now, in wwwroot/js/site.js, add the corresponding jQuery Ajax post method, jQueryAjaxDelete

Following the delete operation, the table is replaced with an HTML string from _ViewAll. That's it; the jQuery Ajax CRUD operations in ASP.NET Core MVC are now complete. For the time being, our application will appear as follows.

Loading Spinner should be added :

There will be some postponement if there is an ongoing operation involving the server. Because of two reasons, displaying a loading spinner instead of an idle interface is recommended.
 
● The user is aware that a back-end request is in progress. You'll have to wait a few more seconds for it to finish.

● Prevents the user from interacting with the interface any further. As a result, the browser will not hang.

Now let's look at how to add a loading spinner in ASP.NET MVC during a jQuery Ajax request. First, add the below div just above the footer within main layout _Layout.cshtml
In site.css, we've just now added the corresponding CSS styles with animation. With the help of the jQuery load event in wwwroot/js/site.js, we've been able to show and hide this spinner during Ajax request-response.
Preventing easy accessibility to action methods is a good idea :

We used a jQuery Ajax GET request to get to the AddOrEdit action method in this application. You can also use the URL /Transaction/AddOrEdit to access the same GET action method. However, because it will only contain the form without a layout, it will not function as expected. We need to block direct access to any action methods that are only defined for jQuery Ajax requests. We can do this by adding a NoDirectAccess attribute to the Helper.cs file.

https://www.codaffection.com/asp-net-core-article/jquery-ajax-crud-in-asp-net-core-mvc/

Now all you have to do is add this attribute to the AddOrEdit GET action method, as shown below.


Conclusion :
Hopefully, the points discussed above using jQuery in Asp.net with modal popups will be useful to you in your project. We've also added some record-adding and record-deleting functions to give you a quick overview of the situation. You can add more features as needed, such as identity core authentication and image uploading and retrieval. For this feature to be implemented, you'll need to read a lot of other information.

Author Bio : Meravath Raju is a Digital Marketer, and a passionate writer, who is working with MindMajix, a top global online training provider. He also holds in-depth knowledge of IT and demanding technologies such as Business Intelligence, Salesforce, Cybersecurity, Software Testing, QA, Data analytics, Project Management and ERP tools, etc.
LATEST ARTICLES