Wednesday, June 24, 2026

ASP.NET Core Razor Page App Basic Setup for fetch API

Razor Page App Setup

STEP 1: Setup the configuration for Razor Page App in Program file

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorPages();
var app = builder.Build();
app.UseDeveloperExceptionPage();
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(options =>
{
    options.MapRazorPages();
});
app.Run();
        
STEP 2: Create UI design for list of anchor tags

@page
@model Razor_Page_App_With_JS.Pages.IndexModel
@{
}

<ul>
    <li id="1"> <a data-item="i1" href="#">This is item number 1</a></li>
    <li id="2"> <a data-item="i2" href="#">This is item number 2</a></li>
    <li id="3"> <a data-item="i3" href="#">This is item number 3</a></li>
    <li id="4"> <a data-item="i4" href="#">This is item number 4</a></li>
    <li id="5"> <a data-item="i5" href="#">This is item number 5</a></li>
</ul>
<div id="displayHere">
    <h2>@Model.Message</h2>
</div>

        
STEP 3: Prepare Client side JavaScript Code for click events

The event listener is attached to all list items when the page is loaded. Then, if a user clicks any anchor, its associated event handler is executed and fetch API runs.

This in turn invokes the server-side handler method. This is given in STEP 4.


<script>
    // add event listener to all list items
    (function(){
        var items = document.querySelectorAll("a");
        items.forEach(anchr=>{
            console.log(anchr);
            anchr.addEventListener('click', async function(event){
                event.preventDefault();
                // fetch API
                fetch("/?handler=PrepareJsonData&id="+ anchr.getAttribute('data-item'),{
                    method:'GET'
                }).catch(err=> console.log("Error during reporting: " + err))
                .then(response=>{
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    return response.json(); // Parse the response as JSON
                })
                .then(data=> {
                    // display the data in UI
                    // Access the 'message' property from the returned JSON object
                    document.getElementById("displayHere").innerHTML = "<h2>RESULT: " + data.message + "</h2>";
                })
                .catch(err => console.log("Error during processing response: " + err));
            });
        });
    })();
</script>

        
STEP 4: Server side handler method

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Text.Json; // for JsonSerializer

namespace Razor_Page_App_With_JS.Pages
{
    public class IndexModel : PageModel
    {
        [BindProperty]
        public string? Message { get; set; } = "";

        // return type IActionResult for returning JSON
        public IActionResult OnGetPrepareJsonData(string? id)
        {
            switch (id)
            {
                
                case "i1":
                    Message = "You have clicked list item number: " + id;
                    break;
                case "i2":
                    Message = "You have clicked list item number: " + id;
                    break;
                case "i3":
                    Message = "You have clicked list item number: " + id;
                    break;
                case "i4":
                    Message = "You have clicked list item number: " + id;
                    break;
                case "i5":
                    Message = "You have clicked list item number: " + id;
                    break;
                default:
                    Message = "Some Error !!!";
                    break;
            }

            // Return the Message as a JSON object
            // You can return a simple string, but it's generally good practice to return a JSON object
            // especially if you might return more data in the future.
            return new JsonResult(new { message = Message });
        }
    }
}

No comments:

Post a Comment

Hot Topics