【问题标题】:ModelState always valid when calling actionresult of an other controllerModelState 在调用其他控制器的 actionresult 时始终有效
【发布时间】:2014-02-12 22:55:03
【问题描述】:

我正在从另一个控制器调用控制器的 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; }
}

我怎样才能让它工作?

【问题讨论】:

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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2011-02-09
    • 1970-01-01
    • 2011-12-31
    • 2019-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多