微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 Razor 页面中传递 id

如何解决在 Razor 页面中传递 id

总的来说,我是 Razor Pages 和 ASP.NET 的新手。 所以我有一个名为 UserInfo。所有视图模型都可以访问此类。 在我的登录页面上,如果登录成功,它将传递 UserId 并将我带回主页面。还会更新 UserInfo 中的所有信息。 当我尝试访问该类以向用户打招呼时,除了在 url 中传递的 id 之外,我无法获得任何其他信息。我什至无法运行 sql 代码解决这个问题。 我如何只传递 id 并使用该 id 查找其他所有内容?是否可以将该 id 保存在某个地方(在课堂或其他地方),这样我就不必传递任何东西?

public IActionResult OnPost()
{
    sqlcon.open();
    sqlcom = new sqlCommand("select* from users where userusername='" + Userinfo.Username + "'",sqlcon);
    sqlDataReader reader = sqlcom.ExecuteReader();
    reader.Read();
    if (reader[2].ToString() == Userpassword)
    {
        Userinfo.UserID = int.Parse(reader[0].ToString());
        Userinfo.Userusername = reader[1].ToString();
        Userinfo.Username = reader[3].ToString();
        return RedirectToPage("/index",new { UserId = Userinfo.UserID });
    }
    else
    {               
        return RedirectToPage("/Login");
    }
}

这里是欢迎用户的地方。它只是说欢迎,因为即使我在登录页面中为它指定了一个名称userinfo.username 仍然是空的?! UserId 是我传递给 url 的变量,它是唯一不为空/空的丁字裤!

@{
    if (Model.UserId != null)
    {
        <h1 class="display-4">Welcome  @Model.UserName</h1>
    }
    else
    {
        <h1 class="display-4">Good to see you!</h1>
        <label class="text-secondary">Please login to access your dashboard</label>
     }
}

解决方法

如果我理解正确,您的应用程序正在重定向到 /Index 页面 (GET),并且 Userinfo 不再具有它在前一个请求 (OnPost) 中的值。

return RedirectToPage("/index",new { UserId = Userinfo.UserID });

我看不到在您的示例中实例化 Userinfo 的位置(可能是控制器构造函数?)但请记住 HTTP 是无状态的。

实现您正在寻找的内容的一种方法是使用 TempData。 TempData 将仅保留一个请求。在重定向到 /index 之前...

TempData["UserInfo"] = Userinfo;
return RedirectToPage("/index",new { UserId = Userinfo.UserID });

在 /index 操作中...

var userInfo = TempData["UserInfo"] as UserInfo;
if (userInfo != null) {

   return View(userInfo);
}

在您的 cshtml 页面上,我假设您已经声明了类似...

@model UserInfo 

另一种方法是使用 UserId 查询参数在 /index 操作中再次查找用户。这样您就不需要 TempData。

作为旁注,请考虑参数化您的 SQL 以防止 SQL 注入。

sqlcom = new SqlCommand("select* from users where userusername='" + Userinfo.Username + "'",sqlcon);

此外,请确保通过 using 语句或 finally块

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。