2015-07-03 128 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

上帝!我產生塔通過重構來實現屬性,我不知道它們是內部的。對不起,這個廢話。非常感謝! –