ASP.NET Core is a modern web development framework by Microsoft. You can build any type of projects – big or small, in this framework. ASP.NET Core is based on Model View Controller (MVC) architecture where any HTTP based request is captured by a Controller which then passes the response to the View.
In the View you can make forms, which on submission, calls the respective Action methods of the Controller. But in this process there will be a page reloading, however you can certainly avoid this page reloading by using jQuery AJAX method.
You can do the following things with the .ajax() method:
Create a new ASP.NET Core application, and next, create a new ASP.NET Core Controller called HomeController inside the Controllers folder.
Create a new Action method called ‘Add’ inside the Controller that has the code shown below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace jquery_ajax_aspnet_core.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public int Add(int number1, int number2)
{
return number1 + number2;
}
}
}
This Add Action method is fairly simple and takes 2 numbers to it’s parameter. It calculates the sum of these numbers and returns the sum at the end.
Create a new ASP.NET Core View called Index.cshtml inside the Controllers ➤ Home folder and add the following jQuery code to it:
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
val1 = "5";
val2 = "2";
$.ajax({
type: "POST",
url: "@Url.Action("Add")",
data: {number1: val1, number2: val2},
dataType: "text",
success: function (msg) {
console.log(msg);
},
error: function (req, status, error) {
console.log(msg);
}
});
});
</script>
Explanation: I defined 2 variables (val1 & val2) that contain 2 numbers which are 5 and 2. Next I defined the .ajax() method of jQuery to call the ‘Add’ action method given in the Controller.
I gave the following values to it:
Open the Startup.cs class of your application and see the routings given inside the Configure() method. In my case it is:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
That means the Action method’s URL based on this routing will be – /Home/Add
a. number1: val1
b. number2: val2
Suppose you have 3 parameters instead of 2 like here. Then the data values would be specified as:
data: {number1: val1, number2: val2, number3: val3},
Note that if the Action method sends the response in any basic data types like int, float, string, double, bool etc , then specify dataType as ‘text’ for in .ajax() method.
Notice that in my success callback method I log the sum of the numbers on the console as shown below.
success: function (msg) {
console.log(msg);
}
It’s time to test the .ajax() method. So run your application and go to the URL of the Index Action method.
Since I added the .ajax() method on the Index action method of the Home controller, so it’s URL in my case is – http://localhost:51685/
Now open the console window and you will see 7 (which is the sum of 2 numbers 5 & 2) printed. See the below image:
You have learned how to invoke action method that returns basic data type like Int by using .ajax() method of jQuery.
Now I will explain how to invoke an action method that returns JSON. I will add a new action method that will return JSON. So first create a new Model called Numbers.cs inside the model folder and add the below code to it:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace jquery_ajax_aspnet_core.Models
{
public class Numbers
{
public int Add { get; set; }
public int Substract { get; set; }
public int Multiply { get; set; }
public decimal Divide { get; set; }
}
}
This class has 4 properties that will contain the Addition, Subtraction, Multiplication and Division of the 2 numbers.
Next, create a new Action method called Calculate inside the Home Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using jquery_ajax_aspnet_core.Models;
namespace jquery_ajax_aspnet_core.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public int Add(int number1, int number2)
{
return number1 + number2;
}
[HttpPost]
public Numbers Calculate(int number1, int number2)
{
Numbers numbers = new Numbers();
numbers.Add = number1 + number2;
numbers.Substract = number1 - number2;
numbers.Multiply = number1 * number2;
numbers.Divide = (decimal)number1 / number2;
return numbers;
}
}
}
This Action method takes 2 numbers in its parameter and has the return type of Numbers object. It first creates an object of ‘Number.cs’ class and stores the ‘Addition, Subtraction, Multiplication and Division’ of the 2 numbers in it’s 4 properties.
In the end it simply returns back the ‘Number’ class object.
Now go to the Index Action method and comment out the previous .ajax() method and add the new .ajax() method as shown below:
$(document).ready(function () {
val1 = "5";
val2 = "2";
$.ajax({
type: "POST",
url: "@Url.Action("Calculate")",
data: {number1: val1, number2: val2},
dataType: "json",
success: function (msg) {
console.log(msg);
},
error: function (req, status, error) {
alert(error);
}
});
@*$.ajax({
type: "POST",
url: "@Url.Action("Add")",
data: {number1: val1, number2: val2},
dataType: "text",
success: function (msg) {
console.log(msg);
},
error: function (req, status, error) {
console.log(error);
}
});*@
});
There are 2 small changes which are in the url of the Action method:
url: "@Url.Action("Calculate")",
And dataType which is set as json:
dataType: "json",
Now re-run your application and check the console window. You will see the JSON response of the arithmetic operations:
{add: 7, substract: 3, multiply: 10, divide: 2.5}
Also see the below image which shown the printed response in the console window:
It should also be noted that you can extract the individual values from this JSON like addition or subtraction values as:
success: function (msg) {
console.log(msg);
console.log(msg.add);
console.log(msg.substract);
console.log(msg.multiply);
console.log(msg.divide);
}
You can download the full codes of this tutorial from the below link:
I hope you liked this tutorial on jQuery AJAX usage in ASP.NET Core. My sincere advice for you is to learn .ajax() method and use it to make your website more user friendly and faster.
Unfortunately the @Url.Action() doesn’t work if the script is linked. Only works if the script is written directly inside the cshtml/razor page.
This is great, and just what I was looking for. It would be even greater if you could extend it to show how the Ajax called “Calculate (…)” method catches an exception (e.g. DivideByZeroException) and nicely returns an error status and a friendly error message, and then how that error is detected in JavaScript and the message consumed?
Hello Dan,
You can extend the Number.cs to have one more property that will contain error string like divide by Zero.
public class Numbers
{
...
public string Error { get; set; }
}
Now you can make a check for 0 value for number 2 in the calculate method:
[HttpPost]
public Numbers Calculate(int number1, int number2)
{
Numbers numbers = new Numbers();
if(number2 == 0)
number.Error = "Divide by 0 error";
else {
numbers.Add = number1 + number2;
numbers.Substract = number1 - number2;
numbers.Multiply = number1 * number2;
numbers.Divide = (decimal)number1 / number2;
}
return numbers;
}
On the AJAX method you can show this error on alert.
alert(msg.error)
Thank you. I appreciate your response and responsiveness. I had done something similar myself, but I wondered if there was a nice way to return something like a StatusCode other than 200 OK (say, 500 Internal Server Error) along with error information. I do something like that returning an error from an ASP.NET Core Web API:
return StatusCode(StatusCodes.Status500InternalServerError, apiError);
No worries – What you suggest, and what similar I have done, will do the job.
You can make
public string Error { get; set; }
to bepublic SCodes Error { get; set; }
. The SCodes will be a class containing properties like “StatusCodeId” of type int, “ErrorMessage” of type string, and so on. It will fulfill your purpose.