简体   繁体   English

具有验证的MVC嵌套视图模型

[英]MVC Nested View Model with Validation

I'm trying to put login and register form into same view. 我正在尝试将登录和注册表单放入相同的视图中。 I did everything suggested in other questions but my problem still not fixed. 我在其他问题上做了所有建议,但我的问题仍然没有解决。

Here is my parent view authentication.cshtml: 这是我的父视图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>

In my partials I use forms like this: 在我的部分中,我使用这样的形式:

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

One of the actions is like this: 其中一个动作是这样的:

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

And here are the models I'm using: 以下是我正在使用的模型:

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

In the action registerVM's Email property has value, but others are null . 在动作中,registerVM的Email属性具有值,但其他属性为null ModelState.IsValid is false . ModelState.IsValidfalse What am I doing wrong? 我究竟做错了什么?

Your properties are not bound because they do not have public setters (only internal) which means the DefaultModelBinder cannot set them (hence they are null and not valid due to the [Required] attributes. Change 您的属性没有绑定,因为它们没有公共setter(仅内部),这意味着DefaultModelBinder无法设置它们(因此它们为null并且由于[Required]属性而无效。

public string FirstName { get; internal set; }

to

public string FirstName { get; set; }

and ditto for all the other properties with internal setters. 和内部制定者的所有其他属性同上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM