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
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.
2
Answers
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:
You can try to use the following code,when clicking the Work button,js function
writeLog()
will call the handlerOnPostUpdatePersonalData
:view(clicking
<input type="button"/>
will not submit the form):js:
result: