Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

139
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda