Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

138
Views
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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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:

  • https://docs.microsoft.com/en-us/aspnet/core/razor-pages/?tabs=visual-studio&view=aspnetcore-6.0#multiple-handlers-per-page
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!