[英]How to display HTML element when user is logged in. (ASP.NET Core MVC, without EF)
[英]How to show the name of the logged user in the Page in ASP MVC without EF
我正在開發一個沒有實體框架的ASP MVC項目。
為了在“歡迎”附近的我的頁面中顯示登錄用戶的名稱(例如“ Welcome John”),我想從表“ Client”中檢索屬性“ Email”的值並將其存儲在列表“ result”中,然后然后將此列表的每個電子郵件與X(即已記錄的電子郵件)進行比較。
在相等的情況下,我檢索與此電子郵件對應的“姓氏”並將其存儲在變量y中。
最后,我將y分配給Session的值。 但是我總是遇到這個錯誤:
ExecuteReader:連接屬性尚未初始化
抱歉,我的編碼質量不好,請考慮我是初學者。
這是我嘗試的:
在控制器中 :
private void connection()
{
string constring = ConfigurationManager.ConnectionStrings["DeliveryCon"].ToString();
con = new SqlConnection(constring);
}
public ActionResult Login()
{
return View();
}
database_Access_layer.db dblayer = new database_Access_layer.db();
[HttpPost]
public ActionResult Login(FormCollection fc, string LastName, string Email)
{
int res = dblayer.Admin_Login(fc["Email"], fc["Password"]);
if (res == 1)
{
Session["currentUser"] = Email;
string z = Email;
connection();
con.Open();
SqlCommand command = new SqlCommand("select Email from Client", con);
List<string> result = new List<string>();
using (var reader = command.ExecuteReader())
{
while (reader.Read())
result.Add(reader.GetString(0));
}
foreach (string x in result)
{
if (x == z)
{
SqlCommand command2 = new SqlCommand("select LastName from Client WHERE Email= @x ", con);
//con.Open();
SqlParameter param = new SqlParameter( "@x", SqlDbType.NVarChar, 16);
param.Value = Session["currentUser"];
command2.Parameters.Add(param);
//con.Open();
string y = command2.ExecuteScalar().ToString();
con.Close();
Session["currentUser"] = y;
}
}
return RedirectToAction("Create", "Client");
Session.RemoveAll();
}
else {
TempData["msg"] = " Email or Password is wrong !";
return RedirectToAction("Index", "Home");
}
}
在我的視圖中Create.cshtml:
<h4>Welcome @if (Session["currentUser"] != null)
{ <h4> @Session["currentUser"].ToString()</h4>}</h4>
您尚未調用Connection()函數來初始化連接,還需要添加conn.Open()來打開與數據庫的連接。
您需要先調用私有方法連接,然后才能在執行讀取器中使用它。
if (res == 1)
{
connection();
您也沒有關閉與
con.Close();
您最好這樣做:
using(SqlConnection con = new SQLConnection(ConfigurationManager.ConnectionStrings["DeliveryCon"].ToString())
{
// other statements
SqlCommand command2 = new SqlCommand("select LastName from Client WHERE Email= @x ", con);
SqlParameter param = new SqlParameter(
"@x", SqlDbType.NVarChar, 16);
param.Value = Session["currentUser"];
command2.Parameters.Add(param);
con.Open();
string y = command2.ExecuteScalar().ToString();
con.Close();
Session["currentUser"] = y;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.