带验证的 MVC 嵌套视图模型

MVC Nested View Model with Validation

我正在尝试将登录和注册表单放入同一个视图中。我做了其他问题中建议的所有事情,但我的问题仍然没有解决。

这是我的父视图authentication.cshtml:

@model Eriene.Mvc.Models.AccountVM
    <div class="row">
        <div class="col-md-6">
            @Html.Partial("_Login", Model.Login ?? new Eriene.Mvc.Models.LoginVM())
        </div>
        <div class="col-md-6">
            @Html.Partial("_Register", Model.Register  ?? new Eriene.Mvc.Models.RegisterVM())
        </div>
    </div>

在我的偏音中,我使用这样的形式:

@using (Html.BeginForm("Register", "Account", FormMethod.Post, new { @id = "login-form", @role = "form", @class = "login-form cf-style-1" }))

其中一个动作是这样的:

[HttpPost]
[AllowAnonymous]
public ActionResult Register(RegisterVM registerVM)
{
    if (ModelState.IsValid)
    {
        User user = new Data.User();
        user.Email = registerVM.Email;
        user.ActivationCode = Guid.NewGuid().ToString();
        user.FirstName = registerVM.FirstName;
        user.LastName = registerVM.LastName;
        user.Password = PasswordHelper.CreateHash(registerVM.Password);
        return RedirectToAction("Index", "Home");
    }

    return View("Authentication", new AccountVM() { Register = registerVM });
}

下面是我使用的模型:

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

public class RegisterVM
{
    [Required]
    public string Email { get; set; }

    [Required]
    public string FirstName { get; internal set; }

    [Required]
    public string LastName { get; internal set; }

    [Required]
    public string Password { get; internal set; }

    [Compare]
    public string PasswordRetype { get; internal set; }
}

public class LoginVM
{
    [Required]
    public string Email { get; set; }

    [Required]
    public string Password { get; set; }

    public bool RememberMe { get; set; }
}

在动作registerVM的Email 属性中有值,但其他的都是nullModelState.IsValidfalse。 我究竟做错了什么?

您的属性未绑定,因为它们没有 public 设置器(仅限内部),这意味着 DefaultModelBinder 无法设置它们(因此它们是 null 并且无效,因为[Required] 个属性。更改

public string FirstName { get; internal set; }

public string FirstName { get; set; }

所有其他具有内部设置器的属性也是如此。