如何检查姓名已有的可用性

时间:2017-02-16 10:50:45

标签: c# asp.net-mvc entity-framework

这里我试图在创建新员工时检查员工姓名的可用性。如果插入的员工姓名已经可用,则创建用户的表格应显示已存在,如果不存在则显示可用消息。

这是我的员工模型类

  [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>

}

3 个答案:

答案 0 :(得分:0)

这行代码没有意义:

employee.Name!=employee.Name

您正在尝试将完全相同的员工姓名与自身进行比较。

相反,您应该按名称搜索db.Employees,例如:

var doesEployeeExist = db.Employees.Any(e => e.Name == employee.Name);

如果&#34; doEployeeExist&#34;这是假的,你知道这个名字没有被使用,你可以自由地创建一个新名称。

但是,您应该知道,人们可能具有相同的名称(第一个和最后一个),特别是随着公司规模的扩大。

答案 1 :(得分:0)

尝试在Any()中使用Linq。像这样:

// This will check if there is an existing name in your database
bool IsEmployeeExist = db.Employees.Any(e => e.Name.Equals(employee.Name));

if(IsEmployeeExist){
  // Show Error Message
} else {
  // Do insert...
}

虽然我认为验证员工姓名过于笼统,因为会有很多人可以使用相同名称。

答案 2 :(得分:0)

您的创建方法应该类似于

if (ModelState.IsValid)
{
    // Check if employee with the same name already exists
    var existingEmployee = db.Employees.FirstOrDefault(e => e.Name == employee.Name);

    // No
    if (existingEmployee == null)
    {
        db.Employees.Add(employee);
        db.SaveChanges();
        return RedirectToAction("Index");
     }
     // Yes
     else
     {
         ViewBag.errorMessage = "Name not available";
         return (ViewBag.errorMessage);
      }           
}