Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

145
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda