Search code examples
javascriptajaxasp.net-corerazor-pages

Add ajax handler on razor page


I am familiar with the traditional MyPage.cshtml and MyPage.cshtml.cs files with OnGetAsync and OnPostAsync methods, but how do I add another handler to the model page that I can call with javascript without doing a full form post?


Solution

  • using System.Collections.Generic;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Mvc.RazorPages;
    using Microsoft.AspNetCore.Antiforgery;
    using Microsoft.AspNetCore.Mvc;
    
    namespace MyApp.Pages;
    
    public class ListModel : PageModel
    {
        private readonly IAntiforgery _antiForgery;
    
        public AntiforgeryTokenSet AntiForgeryToken {get; private set;}
    
        public ListModel(
            IAntiforgery antiForgery
        )
        {
            this._antiForgery = antiForgery;
        }
    
        public async Task OnGet()
        {
            AntiForgeryToken = _antiForgery.GetAndStoreTokens(HttpContext);
        }
    
        public async Task<JsonResult> OnPostWafflesAsync(bool test)
        {
            System.Console.WriteLine("Test approval result="+test);
            return new JsonResult(new {
                received = true,
                test,
            });
        }
    }
    
    <script>
    const formData = new FormData();
    formData.append('test', false);
    fetch(
        `${window.location}?handler=Waffles`,
        {
            method: "POST",
            headers: {
                RequestVerificationToken:`@Model.AntiForgeryToken.RequestToken`,
            },
            body: formData,
    });
    </script>
    

    In this case, we return a JsonResult to be more easily consumable by the javascript (but this example does nothing with the result).

    Note that the handler referenced in the javascript is Waffles instead of OnPostWafflesAsync, related

    References: