1

I am calling an ActionResult of a Controller from an other controller, passing in argument a model. And something strange appens, the ModelState.isValid property is not working when i am doing it this way.

When I am in GiftController and I call the Login ActionResult from AccountController, the model state in AccountController is valid even when it should not.

AccountModel.cs

public class LoginModel
{
    [Required]
    [Display(Name = "Email")]
    [DataType(DataType.EmailAddress, ErrorMessage = "Invalid Email")]

    [...]
}

AccountController.cs

//
    // POST: /Account/Login
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Login(LoginModel model, string returnUrl)
    {
        //Here is the bug ModelState is Always true even when model.Email == null
        if (ModelState.IsValid)
        {
            return RedirectToAction("Index", "PersonalSpace");
        }

        return View(model);
    }

GiftController.cs

public ActionResult RegisterOrLogin(GiftViewModel model)
    {
        AccountController AccControl = new AccountController();
        ActionResult ret = null;
        ret = AccControl.Login(model.login, "");
    }

GiftViewModel.cs

public class GiftViewModel
{

    public LoginModel login { get; set; }
}

How can I make it work ?

Cactus
  • 175
  • 2
  • 12
  • I found what I needed here. http://stackoverflow.com/questions/1269713/unit-tests-on-mvc-validation/3353125#3353125 – Cactus Jan 22 '14 at 18:28

1 Answers1

1

You should not be creating a login controller. If your RegisterOrLogin method needs to call the Login action you should redirect to that Action like so:

public ActionResult RegisterOrLogin(GiftViewModel model)
{
    return RedirectToAction("Login", "Account", new {model.login});
}
Adam Modlin
  • 2,994
  • 2
  • 22
  • 39