這裏我試圖在創建新員工的同時檢查員工姓名的可用性。在創建用戶時,如果插入的員工姓名已經存在,那麼它應該顯示已經存在,如果不存在,則顯示可用消息。
這是我的員工的模型類
如何檢查名稱已有空間
[Table("tblEmployee")]
public class Employee
{
public int EmployeeID { get; set; }
[Required(ErrorMessage ="Name Cannot Be Empty")]
public string Name { get; set; }
[Required(ErrorMessage = "Name Cannot Be Empty")]
public string Gender { get; set; }
[Required(ErrorMessage = "Name Cannot Be Empty")]
public string City { get; set; }
}
下面是創建方法EmployeeController
[HttpPost]
public ActionResult Create(Employee employee)
{
if (ModelState.IsValid)
{
if (employee.Name!=employee.Name)
{
db.Employees.Add(employee);
db.SaveChanges();
return RedirectToAction("Index");
}
else
{
ViewBag.errorMessage = "Name Already Available";
return (ViewBag.errorMessage);
}
}
else
{
return View("Create");
}
}
下面是Create.cshtml
@model Practise.Models.Employee
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Employee</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
</div>
@ViewBag.errorMessage
</div>
<div class="form-group">
@Html.LabelFor(model => model.Gender, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Gender, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Gender, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
'employee.Name!= employee.Name'爲什麼沒有我的名字等於我的名字? –
在'POST'動作中,您應該添加一行代碼以讓所有員工通過'employee.Name'查找它們。如果結果爲'null',那麼你可以將他添加到表中。另外,正如@TânNguyễn所說,'employee.Name!= employee.Name'可能是最沒有用的事情,請注意 –
大多數僱主遲早會意識到,現實世界中的許多人可以使用相同的名稱。使用員工姓名作爲唯一密鑰往往不起作用(如果您強迫員工更改姓名,員工往往會抱怨)。此外,您需要考慮如果兩個人完全同時提交,會發生什麼情況。他們都提交。兩張支票均通過。這兩個新記錄都已創建。噢親愛的!在*最少*處,您應該在數據庫級別強制執行唯一性,並且必須編寫代碼來處理被違反的唯一性。 –