如何将复杂对象发送到 Razor 页面

问题描述 投票:0回答:1

我正在开发 ASP.NET Core 6.0 Identity 项目。我想将

ApplicationUser
对象从
LoginWith2fs.cshtml
页面传递到
Login.cshtml
页面。

这是我的代码 - 登录页面:

return RedirectToPage("./LoginWith2fa", new 
                                        { 
                                            UserSent = user, 
                                            ReturnUrl = returnUrl, 
                                            RememberMe = Input.RememberMe 
                                        });

代码在

LoginWith2fa
页面:

// Created this property in the LoginWith2fa page. Not sure this is needed or not
public ApplicationUser UserSent { get; set; }

public async Task<IActionResult> OnGetAsync(ApplicationUser UserSent, bool rememberMe, string returnUrl = null)
{
    // More code here
    // the  ApplicationUser object has null values in its properties such as username and email
    // However the rememberMe and returnUrl variables have correct values
}
asp.net-core asp.net-identity razor-pages
1个回答
0
投票

您可以临时存储ApplicationUser对象,例如TempData,然后在LoginWith2fa页面中检索它。 检查以下内容:

// Store the ApplicationUser object in TempData
TempData["UserSent"] = user;

return RedirectToPage("./LoginWith2fa", new { returnUrl = returnUrl, rememberMe = Input.RememberMe });

LoginWith2fa页面中的代码:

using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;

public async Task<IActionResult> OnGetAsync(bool rememberMe, string returnUrl = null)
{
    // Retrieve the ApplicationUser object from TempData
    if (TempData.ContainsKey("UserSent"))
    {
        var userData = TempData["UserSent"].ToString();
        var userSent = JsonConvert.DeserializeObject<ApplicationUser>(userData);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.