在 MVC5 中提交时验证单个模型

Validate Single Model on submit In MVC5

让我稍微解释一下我要实现的目标。我有一个视图,其中必须有部分视图,每个部分视图都有两个不同的模型。

1- 登录视图模型 2- RegisterViewModel

我想要实现的是,当登录 Post 操作发生时,如果任何字段留空,则登录模型将 return 编辑到包含所有验证消息的部分视图。

当我 return 在验证字段时出现任何错误的相同视图时,我遇到了问题。

这是一段代码

账户管理员:

  //
        // POST: /Account/Login
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Login(LoginViewModel model)
        {
            if (ModelState.IsValid)
            {

                var user = User.SelectByUserNameAsync(model.UserName,model.Password);
                if (user != null)
                {
                   // var x = User.SignInAsync(model);
                    return Redirect("Home/Index");
                }
                else
                {
                    ViewBag.Model = new RegisterViewModel();
                    ModelState.AddModelError("", "Invalid username or password.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

登录视图:

@{
    Layout = "~/Views/Shared/_LoginLayout.cshtml";
}
<section id="page-title">

    <div class="container clearfix">
        <h1>My Account</h1>
        <ol class="breadcrumb">
            <li><a href="index.aspx">Home</a></li>
            <li><a href="#">Sign-Up</a></li>
            <li class="active">Login</li>
        </ol>
    </div>

</section><!-- #page-title end -->
<!-- Content
============================================= -->
<section id="content">

    <div class="content-wrap">

        <div class="container clearfix">

            <!--Login PartialView-->
            @{Html.RenderPartial("_LoginBox");}

            <!--Login PartialView Ends-->

            <!--Register PartialView-->
            @{Html.RenderPartial("_Register");}

            <!--Register PartialView Ends-->


        </div>

    </div>

</section><!-- #content end -->

但是当页面 return 出现任何错误时,它会向我显示错误

 The model item passed into the dictionary is of type 'ConnexMi.Models.LoginViewModel', but this dictionary requires a model item of type 'ConnexMi.Models.RegisterViewModel'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: The model item passed into the dictionary is of type 'ConnexMi.Models.LoginViewModel', but this dictionary requires a model item of type 'ConnexMi.Models.RegisterViewModel'.

Source Error:


Line 28: 
Line 29:             <!--Register PartialView-->
Line 30:             @{Html.RenderPartial("_Register");}
Line 31: 
Line 32:             <!--Register PartialView Ends-->

你能告诉我我在这段代码中做错了什么吗?谢谢

您将需要一个结合了登录和注册视图模型的视图模型。例如

查看模型

public class LoginVM
{
    [Display(Name = "Email")]
    [Required(ErrorMessage = "Please enter an email address")]
    [DataType(DataType.EmailAddress)]
    [EmailAddress]
    public string Email { get; set; }

    [Required(ErrorMessage = "Please enter a password")]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }
}
public class RegisterVM
{
    // properties for email, password and confirm password
}

public class LoginRegisterVM
{
    public LoginVM Login { get; set; }
    public RegisterVM Register { get; set; }
}

控制器(假定帐户)

public ActionResult Index()
{
    LoginRegisterVM model = new LoginRegisterVM();
    return View(model);
}

[HttpPost]
public ActionResult Login([Bind(Prefix="Login")]LoginVM loginModel)
{
    if (!ModelState.IsValid)
    {
        LoginRegisterVM model = new LoginRegisterVM();
        model.Login = loginModel;
        return View("Index", model);
    }
    // Login and redirect
}
[HttpPost]
public ActionResult Register([Bind(Prefix="Register")]RegisterVM registerModel)
{
    if (!ModelState.IsValid)
    {
        LoginRegisterVM model = new LoginRegisterVM();
        model.Register = registerModel;
        return View("Index", model);
    }
    // Register and redirect
}

查看

@model LoginRegisterVM

@using(Html.BeginForm("Login", "Account", FormMethod.Post)
{
    @Html.LabelFor(m => m.Login.Email)
    @Html.TextBoxFor(m => m.Login.Email)
    @Html.ValidationMessageFor(m => m.Login.Email)
    ... // other properties of login model
    <input type="submit" value="Login" />
}

@using(Html.BeginForm("Register", "Account", FormMethod.Post)
{
    // properties of register model
    <input type="submit" value="Register" />
}