[英]Passing id in Razor Pages
一般來說,我是 Razor 頁面和 ASP.NET 的新手。 所以我有一個名為UserInfo的class 。 所有視圖模型都可以訪問此 class。 在我的登錄頁面上,如果登錄成功,它將傳遞UserId
並將我帶回主頁。 還會更新UserInfo中的所有信息。 當我嘗試訪問 class 以向用戶打招呼時,除了在 url 中傳遞的 id 之外,我無法獲得任何其他信息。 我什至無法運行 SQL 代碼來解決這個問題。 我如何只傳遞 id 並使用該 id 查找其他所有內容? 是否可以將該 id 保存在某處(在 class 或其他地方)所以我不必傳遞任何東西?
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 塊中處理/關閉打開的 SQL 連接以防止泄漏(例如,如果您的 select 語句出於任何原因拋出 SqlException,您希望確保之后清理連接)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.