MacSalty
MacSalty

Reputation: 1242

ASP.net MVC 3 customizing Html.ValidationMessageFor based on model logic

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?

Upvotes: 0

Views: 475

Answers (1)

Rafay
Rafay

Reputation: 31033

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

Upvotes: 1

Related Questions