2015-07-03 169 views
5

我试图把登录和注册表单放入相同的视图。我做了其他问题的所有建议,但我的问题仍然没有解决。MVC嵌套视图模型与验证

这里是我的父视图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的电子邮件酒店有值,但其他人ModelState.IsValid is false。 我在做什么错?

回答

3

你的属性不绑定,因为他们没有公共setter方法(仅供内部使用),这意味着DefaultModelBinder不能设置它们(因此他们null和无效由于[Required]属性。更改

public string FirstName { get; internal set; } 

public string FirstName { get; set; } 

,并同上,对所有与内部制定者的其他属性。

+0

上帝!我产生塔通过重构来实现属性,我不知道它们是内部的。对不起,这个废话。非常感谢! –