0

我一直在阅读与此类似的几个问题,处理自定义@Html.ValidationMessageFor但没有一个涉及我想要做的事情。

我正在处理的当前表单正在编辑数据库中的用户。在此表单中,我需要检查输入的电子邮件是否尚未用于其他用户。我有逻辑,但是如果他们使用已在使用的电子邮件,我没有在页面上显示的自定义验证消息。

控制器代码:

    [HttpPost]
    public ActionResult EditUser(int id, EditUserModel model)
    {
        if (ModelState.IsValid)
        {
            tbl_Users editedUser = tblUsers.EditUser(id, model, HttpContext.User.Identity.Name);
            tblHSDA.EditHSDAS(id, editedUser, model.hsdas, HttpContext.User.Identity.Name);
            return Redirect("~/UserManage/ListActiveUsers");
        }

        if (tblUsers.ValidateEmailInUse(model.Email))
        {
            // change validation message and return View(model);
        }

        tbl_Users tbl_users = db.tbl_Users.SingleOrDefault(item => item.User_id == id);

        ViewBag.hsdas = tblHSDA.GetHSDANameAlpha();
        ViewBag.Username = tbl_users.Username;

        return View(model);
    }

这是在控制器级别完成的吗?

4

1 回答 1

1

根据您的逻辑,如果用户正确填写表格并提供重复的电子邮件,则电子邮件检查部分将永远不会执行

你能做的就是改变ActionResult喜欢

  [HttpPost]
    public ActionResult EditUser(int id, EditUserModel model)
    {
        if (ModelState.IsValid)
        {
            if(!CheckEmail(model.Email)){
            tbl_Users editedUser = tblUsers.EditUser(id, model,  HttpContext.User.Identity.Name);

            tblHSDA.EditHSDAS(id, editedUser, model.hsdas, HttpContext.User.Identity.Name);
            return Redirect("~/UserManage/ListActiveUsers");
           }else{
             ModelState.AddModelError("Email","Email provided is already in use...")
         }
        }       

        tbl_Users tbl_users = db.tbl_Users.SingleOrDefault(item => item.User_id == id);
        ViewBag.hsdas = tblHSDA.GetHSDANameAlpha();
        ViewBag.Username = tbl_users.Username;
        return View(model);
    }

private bool CheckEmail(string email){
 //email check logic
 // return true or false 
}

也看看http://msdn.microsoft.com/en-us/library/gg508808%28v=vs.98%29.aspx

于 2013-03-04T20:25:24.103 回答