How to use jQuery AJAX method to call an Action method in ASP.NET Core

How to use jQuery AJAX method to call an Action method in ASP.NET Core

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.

In this tutorial you will learn how to use the jQuery AJAX method (.ajax())to call an Action method in ASP.NET Core.

You can do the following things with the .ajax() method:

  • 1. Call any Action method of the Controller.
  • 2. Pass values to Action parameters from the View.
  • 3. Get the response from the Action method and show it on the View.
  • 4. All these things happen with no page postback.

Create Action method on the Controller

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 View and jQuery AJAX code

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:

  • 1. type as POST – it means jQuery will make HTTP POST type of request to the ‘Add’ Action.
  • 2. url as @Url.Action(“Add”) – it should be URL to which the Action method can be invoked. I used the Url.Action() method to generate this URL based on the Routing system of my application.

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

  • 3. data as {number1: val1, number2: val2} – here I give the values to the Action method’s parameters which are number1 and number2. The values should be specified in key-value manner like:

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},
  • 4. dataType as text – it specifies the type of response the ‘Add’ action will send. This Action method sends the response in ‘int’ so I used ‘text’.

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.

  • 5. success() – it is the callback function that executes if the .ajax() method executes successfully.
  • 6. error() – it is another callback function that executes if there is some failure when executing the .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);
}
I have used jQuery AJAX extensively when calling ASP.NET Core Web APIs. You can go through this tutorial at Call Web API from jQuery

Testing

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:

Sum of Numbers in Console Window

Action method returning JSON

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.

JSON Web Token (JWT) is a compact URL-safe means of representing claims to be transferred between two parties. I have implemented JWT to make my APIs super secure. You can easily learn it at How to call a JWT secured APIs with jQuery AJAX

In the end it simply returns back the ‘Number’ class object.

Remember that in ASP.NET Core the complex objects are retuned as JSON by default. So that is the trick which I am using here to get JSON response from Action method in the jQuery AJAX.

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:

Arithmetic Operations of Numbers in 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:

Download

Conclusion

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.

SHARE THIS ARTICLE

  • linkedin
  • reddit
yogihosting

ABOUT THE AUTHOR

I hope you enjoyed reading this tutorial. If it helped you then consider buying a cup of coffee for me. This will help me in writing more such good tutorials for the readers. Thank you. Buy Me A Coffee donate

Comments

  1. John says:

    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.

  2. Dan Harrel says:

    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?

    1. yogihosting says:

      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)

  3. Dan Harrel says:

    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.

    1. yogihosting says:

      You can make public string Error { get; set; } to be public 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.

Leave a Reply

Your email address will not be published. Required fields are marked *