简体   繁体   English

从 ASP.NET 内核查看代码获取 JSON

[英]Get a JSON from an ASP.NET Core view code

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在 ASP.NET Core 2.2 应用程序中,我有一个用户页面,我需要在该页面上获取密码重置链接

Bellow is my code, that does not seem to work贝娄是我的代码,这似乎不起作用在此处输入图像描述

the EditUser.cshtml code EditUser.cshtml代码

<script>
    var getUserLink = function () {
        var actionLink = "@Url.Action("ResetPassword", user)";
        $.getJSON(actionLink, function (data) {
            $("#resetLink").html(data["resetLink"]);
        });
    };
</script>

the EditUser.chtml.cs code EditUser.chtml.cs代码

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.我的意思是,当我从cshtml页面单击“获取”按钮时,会询问 JSON,但代码没有在cshtml.cs文件中输入ResetPasword function。 Where is the problem?问题出在哪里?

On razor pages, you use "Handlers" to invoke requests to the razor page you are currently on.在 razor 页面上,您使用“处理程序”来调用对您当前所在的 razor 页面的请求。

So if you want to issue a get request you have to rename your method to follow a certain pattern:因此,如果您想发出 get 请求,您必须重命名您的方法以遵循特定模式:

public class EditUserModel : PageModel
{
    public async Task<JsonResult> OnGetResetPasswordAsync(ApplicationUserModel user)
    {
        /* ...*/
    }
}

And your javascript now becomes the following:您的 javascript 现在变为以下内容:

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与此类似:如果要发出 POST 请求,则需要将处理程序方法命名为OnPostFooOnPostFooAsync ,其余每个 HttpVerbs 都类似

If you want to issue POST requests you have to do a bit more lifting.如果你想发出 POST 请求,你必须做更多的提升。 Read up on it here: https://www.thereformedprogrammer.net/asp-net-core-razor-pages-how-to-implement-ajax-requests/在这里阅读它: https://www.thereformedprogrammer.net/asp-net-core-razor-pages-how-to-implement-ajax-requests/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM