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

65
Vistas
cannot pass data from javascript to Model Function in Razor Pages

I am trying to pass input elemenet to the OnPost method in my Razor Pages project, but method is never taken.

This is my form

                                <p style="text-align: left; font-size: 12px;">Podstawowe dane</p>
                            <p><input type="text" class="form-control" placeholder="Imię" name="name" /></p>
                            <p> <input type="text" class="form-control" placeholder="Nazwisko" name="surname" /></p>
                            <p><input type="text" class="form-control" placeholder="Telefon" name="mobile" /></p>
                            <button type="submit" class="" style="" asp-page-handler="UpdatePersonalData">Dalej</button>
                            <input id="btnWork" type="submit" value="Work" onclick="writeLog(name,surname,mobile);" />

This is my function:

    <script>
    function writeLog(name, surname, mobile) {
        fetch(`?handler=UpdatePersonalData&name=${name}&surname=${surname}&mobile=${mobile}`);
    }
</script>

This is my Model Function:

        }
    public async Task<IActionResult> OnPostUpdatePersonalData(string name, string surname, string mobile)
    {
        var user = await UserManager.GetUserAsync(User);
        _AccountModel.UserId = user.Id;
        _AccountModel.Mail = user.Email;
        await _accountRepository.UpdatePersonalData(_AccountModel, name, surname, mobile);
        return RedirectToPage("/Account/DataForm/CompanyData");
    }

If you could help i will be grateful

##UPDATE

After conversation with user at stackoverflow

this is whole

https://pastebin.com/WxCihCWM

At first i thought i can do multiple post request like with static form, but as far as i can see i have to update it at once.

almost 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

fetch sends a GET request by default you need to configure it to send POST. You also need to pass the antiforgery token.

https://learn.microsoft.com/en-us/aspnet/core/security/anti-request-forgery?view=aspnetcore-6.0#javascript-1

Try this:


@inject Microsoft.AspNetCore.Antiforgery.IAntiforgery Antiforgery
@{
    var requestToken = Antiforgery.GetAndStoreTokens(HttpContext).RequestToken;
}

<p style="text-align: left; font-size: 12px;">Podstawowe dane</p>
<p><input id="name" type="text" class="form-control" placeholder="Imię" name="name" /></p>
<p><input id="surname" type="text" class="form-control" placeholder="Nazwisko" name="surname" /></p>
<p><input id="mobile" type="text" class="form-control" placeholder="Telefon" name="mobile" /></p>
<input id="btnWork" type="submit" value="Work" onclick="writeLog()" />

<input id="RequestVerificationToken" type="hidden" value="@requestToken" />

@section Scripts {
    <script>
        function writeLog() {
            const name = document.getElementById('name').value;
            const surname = document.getElementById('surname').value;
            const mobile = document.getElementById('mobile').value;

            const url = `?handler=UpdatePersonalData&name=${name}&surname=${surname}&mobile=${mobile}`;
                        
            fetch(url, {
                method: 'POST',
                headers: {
                    RequestVerificationToken:
                        document.getElementById('RequestVerificationToken').value
                }
            });
        }
    </script>
}
almost 4 years ago · Santiago Trujillo Denunciar

0

You can try to use the following code,when clicking the Work button,js function writeLog() will call the handler OnPostUpdatePersonalData:

view(clicking <input type="button"/> will not submit the form):

<form method="post" id="myForm">
    <p style="text-align: left; font-size: 12px;">Podstawowe dane</p>
    <p><input type="text" class="form-control" placeholder="Imię" name="name" /></p>
    <p> <input type="text" class="form-control" placeholder="Nazwisko" name="surname" /></p>
    <p><input type="text" class="form-control" placeholder="Telefon" name="mobile" /></p>
    <button type="submit" class="" style="" asp-page-handler="UpdatePersonalData">Dalej</button>
    <input id="btnWork" type="button" value="Work" onclick="writeLog()" />
</form>

js:

function writeLog() {
            $.ajax({
                type: "POST",
                url: "?handler=UpdatePersonalData",
                data: $("#myForm").serialize(),
                headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
                success: function(data) {

                }
            });

        }

result:

enter image description here

almost 4 years ago · Santiago Trujillo 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