0

I've been reading over several of the questions similar to this, dealing with customizing the @Html.ValidationMessageFor but none of them touched on what I'm looking to do.

The current form I'm working on is editing a user in a database. Within this form I need to check that the email being entered is not already used for another user. I have the logic, but what I don't have is the custom validation message to appear on the page if they use an already in-use email.

Controller code:

    [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);
    }

Is this something done at the Controller level?

1 Answer 1

1

as per your logic the email check part will never execute if the user fills in the form correctly and provides a duplicate email

what you can do is change the ActionResult like

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

also have a look at http://msdn.microsoft.com/en-us/library/gg508808%28v=vs.98%29.aspx

Sign up to request clarification or add additional context in comments.

1 Comment

Excellent. Thank you for logic placement, this has solved my problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.