【发布时间】:2021-02-23 13:25:21
【问题描述】:
当我尝试在 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");
}
当我转到编辑页面并尝试更改 URL 中的id 时,任何int 的答案都不是空的,而是空的。这是我制作教程的链接enter link description here
这是图片,这是我的问题。我在 URL 中写了一个在我的数据库中不存在的 id,但它仍然返回一个 null 和空 id。 [2]:https://i.stack.imgur.com/HC9yx.png
请给点想法好吗?
【问题讨论】:
-
发生这种情况是因为 Empoyee 永远不会为空。您是否看到创建新员工的行?如果没有记录,则返回空员工
-
问题与GetEmployeeData方法有关,即使数据库中不包含特殊的Employee,它仍然返回一个新的Employee实例。正如 Saravanan 所说,先尝试检查 Employee 是否存在,然后返回一个新的 Employee 实例。
标签: c# sql-server asp.net-core ado.net razor-pages