How to use Ajax in Razor pages in ASP.NET Core 3 and higher

In this post, I'm going to show you how to use Ajax in Razor pages without using of any controller.

  1. Create a new ASP.NET Core Web Application project (ASP.NET Core 3.1 or higher / Web Application)

  1. Open the Index.cshtml under the Pages folder and paste below code:
@page

@model IndexModel

@{

    ViewData["Title"] = "Home page";

}



<div class="text-center">

    <h1 class="display-4">Welcome</h1>



    <input id="inputId"/>

    <button class="btn btn-outline-info" onclick="getData(document.getElementById('inputId').value)"> Call Ajax</button>

    <p id="result"></p>

</div>



<script>
    function getData(ID) {

        $.ajax({

            data:{id:ID},

            url: '/Index?handler=Test',

            type: 'GET',

            success: function (data) {

                document.getElementById('result').innerHTML = data;
            },

            error: function () {

                alert("errror");
            }

        });
    }

</script>
  1. Open the Index.cshtml.cs under the Pages folder and paste below code:

 

[HttpGet]
public IActionResult OnGetTest(string id)
{
     string result = "You sent me this ID: " + id + "in time: " + DateTime.Now.ToString();
     return new JsonResult(result);
}

In which, OnGetTest in IActionResult is the name of Ajax function or API. Actually, OnGet is a keyword and Test is the name of your Ajax function. Generally, the format of an Ajax function is following:

OnGet+"Name of your Ajax"

When you want to call this Ajax in Razor pages you have to write ?handler instead of the OnGet.

Recent Comments