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 Controller called ‘HomeController’ inside the ‘Controllers’ folder.

Create a new Action method called ‘Add’ inside the Controller that has the code shown below:

[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 View called Add.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) {
                alert(msg);
            },
            error: function (req, status, error) {
                alert(error);
            }
        });	
    });
</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.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        template: "{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 am printing the response on the console window of the browser.

success: function (msg) {
    console.log(msg);
},

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:

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:

[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.

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

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 -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on "ASP.NET Core, jQuery, EF Core, SEO, jQuery, HTML" and more.

Leave a Reply

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