In an ASP.NET Core 2.2 appliation, I have a user page and I need to obtain on that page a password reset link
Bellow is my code, that does not seem to work
the EditUser.cshtml
code
<script>
var getUserLink = function () {
var actionLink = "@Url.Action("ResetPassword", user)";
$.getJSON(actionLink, function (data) {
$("#resetLink").html(data["resetLink"]);
});
};
</script>
the EditUser.chtml.cs
code
public class EditUserModel : PageModel
{
/// ...
public async Task<JsonResult> ResetPassword(ApplicationUserModel user)
{
var appUser = new ApplicationUser
{
UserName = user.Email,
Email = user.Email,
DisplayName = user.Name,
OrganizationID = user.OrganizationID,
EmailConfirmed = true
};
var code = await userManager.GeneratePasswordResetTokenAsync(appUser);
var callbackUrl = Url.Page("/Account/ResetPassword",
pageHandler: null,
values: new { code },
protocol: Request.Scheme);
return new JsonResult(new { resetLink = callbackUrl });
}
}
I mean, when I click on the "Obtain" button from the cshtml
page, the JSON is asked, but the code does not enter the ResetPasword
function in the cshtml.cs
file. Where is the problem?
On razor pages, you use "Handlers" to invoke requests to the razor page you are currently on.
So if you want to issue a get request you have to rename your method to follow a certain pattern:
public class EditUserModel : PageModel
{
public async Task<JsonResult> OnGetResetPasswordAsync(ApplicationUserModel user)
{
/* ...*/
}
}
And your javascript now becomes the following:
var getUserLink = function () {
var actionLink = "./?handler=ResetPassword";
$.getJSON(actionLink, function (data) {
$("#resetLink").html(data["resetLink"]);
});
};
Analog to this: If you want to issue a POST request, you need to name your handler method
OnPostFoo
or OnPostFooAsync
and similar for each of the remaining HttpVerbs
If you want to issue POST requests you have to do a bit more lifting. Read up on it here: https://www.thereformedprogrammer.net/asp-net-core-razor-pages-how-to-implement-ajax-requests/