새 직원을 만드는 동안 직원 이름 가용성을 확인하려고합니다. 삽입 된 직원 이름이 이미 사용 가능하면 사용자를 생성하는 동안 테이블이 이미 존재하고 그렇지 않으면 사용 가능한 메시지가 표시됩니다.
여기
이름을 이미 확인하는 방법
[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; }
}
아래는 아래
[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");
}
}
이
@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>
Create.cshtml
인가에는 EmployeeController에서 방법을 만들기가 내 직원 모델 클래스 당신은 자신과 동일한 직원의 이름을 비교하려고
employee.Name!=employee.Name
:
}
'employee.Name과 같아야 만들! = employee.Name' 이유는 무엇입니까 내 이름과 동일하지 내 이름? –
'POST' 액션에서 라인 코드를 추가하여 모든 직원들이'employee.Name'에 의해 그것들을 찾도록해야합니다. 결과가 'null'이면 테이블에 추가 할 수 있습니다. 또한, @ TânNguyễn이 말한 것처럼,'employee.Name! = employee.Name'은 아마도 가장 쓸모없는 일일 것입니다. –
대부분의 고용주는 조만간, 현실 세계의 많은 사람들이 같은 이름을 가질 수 있음을 깨닫게 될 것입니다 . 직원 이름을 고유 키로 사용하면 직원이 자신의 이름을 변경하도록 요청하면 불만을 토로하는 경향이 있습니다. 또한 두 사람이 정확히 같은 시간에 제출하면 어떻게 될지 고려해야합니다. 그들은 둘 다 복종한다. 두 수표는 모두 통과합니다. 두 개의 새 레코드가 만들어집니다. 이런! 적어도 *에서는 데이터베이스 수준에서 고유성을 강제해야하며 위반되는 고유성에 대처할 수있는 코드를 작성해야합니다. –