调用另一个控制器的actionresult时,ModelState始终有效

时间:2014-01-22 17:59:42

标签: c# asp.net-mvc-4

我从另一个控制器调用Controller的ActionResult,传入参数模型。奇怪的是,当我这样做时,ModelState.isValid属性不起作用。

当我在GiftController中并从AccountController调用Login ActionResult时,AccountController中的模型状态即使不应该也是有效的。

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

我怎样才能让它发挥作用?

1 个答案:

答案 0 :(得分:1)

您不应该创建登录控制器。如果您的RegisterOrLogin方法需要调用Login操作,您应该重定向到该Action,如下所示:

public ActionResult RegisterOrLogin(GiftViewModel model)
{
    return RedirectToAction("Login", "Account", new {model.login});
}