In the previous Post on ASP.NET MVC We saw how to create Notifications in MVC using JQuery plugin. In this post we will see How to create ASP.NET MVC JQuery AJAX request (HttpPost and HttpGet) to controllers. We will post data on our controller function which stores data in SQL Database and also create an AJAX HttpGet request which we return us current DateTime of the system.
What is AJAX?
AJAX stands for Asynchronous JavaScript and XML. AJAX helps in posting data and getting response from the server after web page is loaded without refreshing the entire page. Using AJAX we can dynamically update content of our web page without reloading the complete page.
Creating AJAX calls to ASP.NET MVC Controller:
In your MVC project create a new Model class with name Products.cs
and edit it as below:
Models > Products.cs:
namespace MVCAJax.Models { public class Products { public string ProductName { get; set; } public string Price { get; set; } public string Category { get; set; } } }
Create a new MVC controller with name ProductsController.cs
and edit it as below. This controller contains two functions (HttpPost and HttpGet methods), which will be called from MVC View using JQuery AJAX requests.
Controllers > ProductsController.cs:
using MVCAJax.Models; using System; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Web.Mvc; namespace MVCAJax.Controllers { public class ProductsController : Controller { // GET: Products public ActionResult Index() { return View(); } [HttpPost] public ActionResult addProducts(Products obj) { try { SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["connectionString"].ToString()); SqlCommand cmd = new SqlCommand("AddProducts",con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@ProductName", obj.ProductName); cmd.Parameters.AddWithValue("@Category", obj.Category); cmd.Parameters.AddWithValue("@Price", obj.Price); con.Open(); cmd.ExecuteNonQuery(); cmd.Dispose(); con.Close(); return Json(new { data = "success" }, JsonRequestBehavior.AllowGet); } catch(Exception ex) { return Json(new { data = "Error:" + ex.Message.ToString() }, JsonRequestBehavior.AllowGet); } } [HttpGet] public ActionResult getDateTime() { return Json(new { data = "System DateTime : "+ DateTime.Now.ToString("dd-MMM-yyyy hh:mm:ss tt") }, JsonRequestBehavior.AllowGet); } } }
First we will create an AJAX HttpGet request to the controller method for getting System DateTime. Add a View for the index method edit it as below:
Views > Products > Index.cshtml:
@model MVCAJax.Models.Products @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>ASP.NET MVC - Ajax Calls</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous"> <script src="~/Scripts/notify.min.js"></script> <style> body { padding: 10px !important; margin: 10px !important; background-color: #f6f6f6; } </style> </head> <body> <h5>ASP.NET MVC - JQuery AJAX Calls to Controller</h5> <div> <hr /> <table class="table-condensed"> <tr> <td> Product: </td> <td> <input type="text" class="form-control" id="ProductName" placeholder="Enter Product name" /> </td> </tr> <tr> <td> Category: </td> <td> <input type="text" class="form-control" id="Category" placeholder="Enter Category" /> </td> </tr> <tr> <td> Price: </td> <td> <input type="text" class="form-control" id="Price" placeholder="Enter Price" /> </td> </tr> </table> <br /> <input type="button" class="btn btn-primary" value="Submit" id="btnAdd" /> <input type="button" class="btn btn-danger" value="Get current DateTime" id="btnDateTime" /> </div> <script> $('#btnAdd').click(function () { $.ajax({ type: "POST", url: "http://localhost:32413/Products/addProducts", data: { ProductName: $('#ProductName').val(), Category: $('#Category').val(), Price: $('#Price').val() }, success: function (data) { $('#btnAdd').notify(JSON.parse(JSON.stringify(data)).data, { globalPosition: 'left center', autoHide: false, className: 'success' }) $('#Price').val(''); $('#ProductName').val(''); $('#Category').val(''); } }); }); $('#btnDateTime').click(function () { $.ajax({ type: "GET", url: "http://localhost:32413/Products/getDateTime", success:function(data) { $.notify(JSON.parse(JSON.stringify(data)).data, { globalPosition: 'top center', autoHide: true, className:'info' }) } }); }); </script> </body> </html>
When you run this form, the btnDateTime
JQuery click event makes an call to the controller for getting system DateTime and displays it as a Toast Notification. You can download the javascript for Notification JQuery plugin from this link and paste it inside the Scripts folder of your project. The data is returned in JSON format and after parsing it, it is shown to the user.
Making an AJAX HttpPost request to controller:
Create a new table in your SQL database with name tblProducts like below:
SQL Script:
Create database [ProductsDB] USE [ProductsDB] CREATE TABLE [dbo].[tblProducts]( [ProductId] [int] IDENTITY(1,1) NOT NULL, [Product] [nvarchar](50) NOT NULL, [Category] [nvarchar](50) NULL, [Price] [nvarchar](50) NULL ) --Stored Procedure create proc AddProducts ( @ProductName nvarchar(50), @Category nvarchar(50), @Price int ) as begin Insert into tblProducts (Product,Category,Price) values (@ProductName, @Category, @Price) end;
In this table we will store the data entered in the MVC View form using AJAX request. In your web.config file create a connectionString app key under Configurations like below:
<configuration> <appSettings> <add key="webpages:Version" value="3.0.0.0"/> <add key="webpages:Enabled" value="false"/> <add key="ClientValidationEnabled" value="true"/> <add key="UnobtrusiveJavaScriptEnabled" value="true"/> <add key="connectionString" value="Data Source=vibes\sql2014;Initial Catalog=ProductsDB;Persist Security Info=True;User ID=asp;Password=123"/> </appSettings>
My Database name is ProductsDB. Change it according to your Database properties. Now when you enter the data in the form and press on the submit button, an AJAX call is made to the addProducts function which simply add data to the SQL database table and returns JSON data in return.
[HttpPost] public ActionResult addProducts(Products obj) { try { SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["connectionString"].ToString()); SqlCommand cmd = new SqlCommand("AddProducts",con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@ProductName", obj.ProductName); cmd.Parameters.AddWithValue("@Category", obj.Category); cmd.Parameters.AddWithValue("@Price", obj.Price); con.Open(); cmd.ExecuteNonQuery(); cmd.Dispose(); con.Close(); return Json(new { data = "success" }, JsonRequestBehavior.AllowGet); } catch(Exception ex) { return Json(new { data = "Error:" + ex.Message.ToString() }, JsonRequestBehavior.AllowGet); } }
AJAX call is made using JQuery button click function, which is posting data to the controller function in form of JSON data of our Products.cs
model which we created initially.
<script> $('#btnAdd').click(function () { $.ajax({ type: "POST", url: "http://localhost:32413/Products/addProducts", data: { ProductName: $('#ProductName').val(), Category: $('#Category').val(), Price: $('#Price').val() }, success: function (data) { $('#btnAdd').notify(JSON.parse(JSON.stringify(data)).data, { globalPosition: 'left center', autoHide: false, className: 'success' }) $('#Price').val(''); $('#ProductName').val(''); $('#Category').val(''); } }); }); </script>
Once the call is completed, results is shown in form of toast notifications using Notify.js JQuery plugin. In this post on How to show Notifications in HTML pages, I have explained different formats Notifications using this JQuery plug-in. You can download entire source code along with SQL script using below link.
Output: