远程电子邮件验证仅在某些视图中有效吗?

时间:2017-02-03 16:57:00

标签: c# asp.net-mvc razor remote-validation

我的模型中有一个类似于

的电子邮件属性
    [Required(ErrorMessage ="Email Address is required.")]
    [EmailAddress(ErrorMessage = "Invalid Email Address")]
    [Remote("checkEmailValidate", "Employee", HttpMethod = "POST", ErrorMessage ="User with this Email already exists")]
    public virtual string EmailAddress { get; set; }

我有两个使用此模型的不同视图,第一个是创建用户时;

<div class="form-group">
    @Html.LabelFor(model => model.EmailAddress, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.EmailAddress, new { htmlAttributes = new { @class = "form-control", placeholder = "Email Address" } })
        @Html.ValidationMessageFor(model => model.EmailAddress, "", new { @class = "text-danger" })            
    </div>
</div>

第二个是编辑用户帐户时

<div class="form-group">
    @Html.LabelFor(model => model.EmailAddress, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.EmailAddress, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.EmailAddress, "", new { @class = "text-danger" })
    </div>
</div>

现在我的控制器看起来像这样

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "EmployeeId,FirstName,LastName,UniversityID,EmailAddress,Department,MinimumHours,ApproverEmailAddress,IsActive,Type,NotificationRecipients,ReviewerFor,IsDepartmentHR,IsAdministrator")] Employee employee)
    {
        if (checkEmail(employee.EmailAddress))
        {
            if (IsAuthorized(AuthorizationType.Either))
            {
                if (ModelState.IsValid)
                {
                    if (IsAuthorized(AuthorizationType.Administrator))
                    {
                        db.Employees.Add(employee);
                        db.SaveChanges();
                        Utilities.AuditEvent(loggedOnEmployee, employee, Utilities.AuditEventType.AddEmployee);
                        return RedirectToAction(actionName: "Index");
                    }
                    if (IsAuthorized(AuthorizationType.DepartmentHR))
                    {
                        employee.Department = loggedOnEmployee.Department;
                        db.Employees.Add(employee);
                        db.SaveChanges();
                        Utilities.AuditEvent(loggedOnEmployee, employee, Utilities.AuditEventType.AddEmployee);
                        return RedirectToAction(actionName: "Index");
                    }
                }
                return View(employee);
            }
            else
            {
                return RedirectToAction(actionName: "Restricted");
            }
        }
        else
        {
            return RedirectToAction(actionName: "Create");
        }

    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include = "EmployeeId,FirstName,LastName,UniversityID,EmailAddress,Department,MinimumHours,ApproverEmailAddress,IsActive,Type,NotificationRecipients,ReviewerFor,IsAdministrator,IsDepartmentHR")] Employee employee)
    {
        if (IsAuthorized(AuthorizationType.Either))
        {
            if (ModelState.IsValid)
            {
                if (IsAuthorized(AuthorizationType.Administrator))
                {
                    Employee employeeInDb = db.Employees.Find(employee.EmployeeId);
                    db.Entry(employeeInDb).CurrentValues.SetValues(employee);
                    db.Entry(employeeInDb).State = EntityState.Modified;
                    db.SaveChanges();
                    Utilities.AuditEvent(loggedOnEmployee, employeeInDb, Utilities.AuditEventType.EditEmployee);
                    return RedirectToAction(actionName: "Index");
                }

                if (employee.Department != loggedOnEmployee.Department)
                {
                    return RedirectToAction(actionName: "Restricted");
                }
                else
                {
                    Employee employeeInDb = db.Employees.Find(employee.EmployeeId);
                    db.Entry(employeeInDb).CurrentValues.SetValues(employee);
                    db.Entry(employeeInDb).State = EntityState.Modified;
                    db.SaveChanges();
                    Utilities.AuditEvent(loggedOnEmployee, employeeInDb, Utilities.AuditEventType.EditEmployee);
                    return RedirectToAction(actionName: "Index");
                }
            }
            return View(employee);
        }
        else
        {
            return RedirectToAction(actionName: "Restricted");
        }
    }

这是我的问题:

我想确保不使用现有的电子邮件地址创建用户,但我希望能够编辑现有用户。现在发生的事情是创建用户时,它运行正常,但在编辑用户时,我仍然会收到用户已存在消息。如何解决此问题,以便在编辑视图中不会弹出警告?

2 个答案:

答案 0 :(得分:1)

创建单独的类Model public class CreateEmployee : Employee以与Create操作一起使用。覆盖新类的EmailAddress属性,并将Remote验证程序添加到CreateEmployee,但不是Employee

像这样:

public class Employee
{
    [Required(ErrorMessage ="Email Address is required.")]
    [EmailAddress(ErrorMessage = "Invalid Email Address")]
    public virtual string EmailAddress { get; set; }
}

public class CreateEmployee : Employee
{
    //Existing members of Employee should be preserved. if there are any so your code should continue to work.

    [Required(ErrorMessage ="Email Address is required.")]
    [EmailAddress(ErrorMessage = "Invalid Email Address")]
    [Remote("checkEmailValidate", "Employee", HttpMethod = "POST", ErrorMessage ="User with this Email already exists")]
    public override string EmailAddress { get; set; }
}

答案 1 :(得分:1)

这些是ViewModel重要性发挥作用的场景,您必须为Create Employee View创建两个不同的ViewModel,例如EditEmployee,然后使用它的相应ViewModel绑定每个视图。

你的两个视图模型都是:

public class CreateEmployeeViewModel
{
    [Required(ErrorMessage ="Email Address is required.")]
    [EmailAddress(ErrorMessage = "Invalid Email Address")]
    [Remote("checkEmailValidate", "Employee", HttpMethod = "POST", ErrorMessage ="User with this Email already exists")]
    public virtual string EmailAddress { get; set; }
}

并在 EditEmployeeViewModel 中,您可以删除不想应用的属性:

public class EditEmployeeViewModel
{
    [Required(ErrorMessage ="Email Address is required.")]
    [EmailAddress(ErrorMessage = "Invalid Email Address")]
    public virtual string EmailAddress { get; set; }
}