(ASP.NET Core) Bare minimum code for a parameterized AJAX GET Request to a C# function

The following project has a textbox with a send button. The click event fires an AJAX GET request and sends a string parameter to an ASP.NET Core application, which responds by converting the parameter to its uppercase equivalent. The client side script has been written using pure javascript.
(Rev. 31-Oct-2024)

Categories | About |     |  

Parveen,

First of all create an ASP.NET Core project based on an empty template, and configure the startup.cs file for razor pages as explained here (ASP.NET Core AJAX) Ajax based POST of a Razor Page

Next add a razor page called Index - you will get 2 files: Index.cshtml and Index.cshtml.cs. Ensure that these files are inside a folder called "Pages" - otherwise no requests will be processed. The spellings of the Pages folder must be exactly the same.

Complete the code exactly as explained in the next sections.

The Markup for Index.cshtml file

Write this markup in the index.cshtml razor page -

@page

@model MasterSlaveAjax.Pages.IndexModel

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

<h1>Ajax GET Request</h1>

<span id="pw" style="color:red;"></span>

<table>
  <tr>

    <td>
      Type:
    </td>

    <td>
      <input id="txtIn" />
    </td>

  </tr>

  <tr>

    <td colspan="2" style="text-align:right">

      <button id="btnSend">Send</button>

    </td>

  </tr>

</table>

<script type="text/javascript">

  (function () {

    // attach onclick to the send button 
    btnSend.addEventListener("click", async function (event) {

      // show please wait 
      pw.innerHTML = "please wait...";

      // the url for the GET request 
      const url = "/?handler=MakeUpper&param=" + txtIn.value;

      // aysnchronous fetch ajax 
      fetch(url,
        {
          method: "GET"
        }
      )
        // if any exceptions - log them 
        .catch(err => console.log("network error: " + err))

        .then(response => {

          // read json from the response stream 
          response.json().then(data => {

            // display the received data 
            pw.innerHTML = "from GET request: " + data;

          });

        })
    });

  })();

</script>

Take note of these points:

  1. The namespace should be of your own project here: @model MasterSlaveAjax.Pages.IndexModel
  2. The GET request goes to the home - index - page and carries 2 parameters: handler and param. The parameter handler contains the name of the C# method that will receive this request, and param is the string parameter that will be accepted by the C# method (handler).

Video Explanation
(code given after this video)

Please watch the following youtube video:

The Index.cshtml.cs backing class

Write this code in the IndexModel backing class of the csharp file:

There is a naming rule for the C# GET handler - the method should be prefixed with OnGet. So, if the handler is MakeUpper, then the C# method should be OnGetMakeUpper(string param)
using Microsoft.AspNetCore.Mvc;

using Microsoft.AspNetCore.Mvc.RazorPages;

using System.Threading.Tasks;

namespace MasterSlaveAjax.Pages
{

  public class IndexModel : PageModel
  {

    // handler is MakeUpper 
    public async Task<JsonResult> OnGetMakeUpper(string param)
    {

      // artifical delay 
      await Task.Delay(500);

      string ret = string.Empty;

      if(!string.IsNullOrEmpty(param))
      {

        ret = param.ToUpper();

      }

      return new JsonResult(ret) ;

    }

  }

}

Run the project to see that the data is indeed sent as an Ajax GET call. It shows a "please wait" message and then displays the same input string converted to uppercase.


This Blog Post/Article "(ASP.NET Core) Bare minimum code for a parameterized AJAX GET Request to a C# function" by Parveen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.