[英]Get data from the Database using ADO.NET in razor pages
當我嘗試在 URL 中搜索不存在的員工時,URL 返回一個肯定的響應,就好像它在數據庫中不存在的id
之后找到員工一樣,但它是空的,而不是將我重定向到未NotFound
頁面。 下面是從數據庫中檢索數據的代碼:
public Employee GetEmployeeData(int? id)
{
Employee employee = new Employee();
using (SqlConnection connection = new SqlConnection(connectionString))
{
string sqlQuery = "SELECT * FROM tblEmployee WHERE EmployeeID= " + id;
SqlCommand commend = new SqlCommand(sqlQuery, connection);
connection.Open();
SqlDataReader readData = commend.ExecuteReader();
while (readData.Read())
{
employee.Id = Convert.ToInt32(readData["EmployeeID"]);
employee.Name = readData["Name"].ToString();
employee.Gender = readData["Gender"].ToString();
employee.Department = readData["Department"].ToString();
employee.City = readData["City"].ToString();
}
}
return employee;
}
這是我的EditEmployee.cshmtl.cs
中的OnGet
和OnPost
方法:
public ActionResult OnGet(int? id)
{
if (id == null)
{
return RedirectToPage("/NotFound");
}
Employee = objemployee.GetEmployeeData(id);
if (Employee == null)
{
return RedirectToPage("/NotFound");
}
return Page();
}
public ActionResult OnPost()
{
if (!ModelState.IsValid)
{
return Page();
}
objemployee.UpdateEmployee(Employee);
return RedirectToPage("./EmployeeIndex");
}
當我將 go 轉到編輯頁面並嘗試更改 URL 中的id
時,答案不是 null 對於任何int
而是空的。 這是我制作教程的鏈接,並進行了一些小改動在此處輸入鏈接描述
這是圖像,這是我的問題。 我在 URL 中寫了一個在我的數據庫中不存在的 id,但它仍然返回 null 和空 id。 [2]: https://i.stack.imgur.com/HC9yx.png
請給點想法好嗎?
您應該在未能獲取數據時返回 null,而不是始終返回一個新的Employee
實例。 嘗試以下代碼更改
using (SqlConnection connection = new SqlConnection(connectionString))
{
string sqlQuery = "SELECT * FROM tblEmployee WHERE EmployeeID= " + id;
SqlCommand commend = new SqlCommand(sqlQuery, connection);
connection.Open();
SqlDataReader readData = commend.ExecuteReader();
if(!readData.HasRows) return null;
Employee employee = new Employee();
while (readData.Read())
{
employee.Id = Convert.ToInt32(readData["EmployeeID"]);
employee.Name = readData["Name"].ToString();
employee.Gender = readData["Gender"].ToString();
employee.Department = readData["Department"].ToString();
employee.City = readData["City"].ToString();
}
return employee;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.