ここでは、新しい従業員の作成中に従業員の名前の可用性を確認しようとしています。挿入された従業員名が既に利用可能である場合にユーザを作成する際には、それが既に存在するはずのテーブルであり、そうでなければ利用可能なメッセージを表示する。ここ
は私の従業員のモデルクラスの下
名前を確認する方法
[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
@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>
以下
[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");
}
}
でメソッドを作成することですですあなたが自分自身とまったく同じ従業員の名前を比較しようとしている
employee.Name!=employee.Name
:
}
'employee.Nameのようになります作成!= employee.Name'なぜ私の名前と同じではない、私の名前は? –
'POST'アクションでは、' employee.Name'ですべての従業員を見つけるための行コードを追加する必要があります。結果が 'null'の場合、彼をテーブルに追加することができます。また、@TânNguyễnが言ったように、 'employee.Name!= employee.Name'はおそらく最も役に立たないことです。注意を払うこと –
ほとんどの雇用者は、現実世界の多くの人が同じ名前。従業員の名前をユニークなキーとして使用することは機能しません(従業員は自分の名前を変更すると不平を言う傾向があります)。また、2人が正確に同じ時間に提出すれば、何が起こるかを考慮する必要があります。両方とも提出する。両方の小切手が合格。両方の新しいレコードが作成されます。まあ! *少なくとも*では、データベースレベルで一意性を強制する必要があります。また、一意性違反に対処するためのコードを記述する必要があります。 –