2015-07-03 11 views
5

Próbuję umieścić formularz logowania i rejestracji w tym samym widoku. Zrobiłem wszystko, co zasugerowałem w innych kwestiach, ale mój problem nie został naprawiony.Widok zagnieżdżonego modelu MVC z walidacją

Oto mój widok rodzic 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> 

W moich podszablonów używam formy tak:

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

Jednym z działań jest tak:

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

A oto modele, których używam:

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

w nieruchomości Wysłać registerVM Akcja zawiera wartość, ale inni są zerowej. ModelState.IsValid to false. Co robię źle?

Odpowiedz

3

Twoje właściwości nie są związani, ponieważ nie mają ustawiające publicznych (tylko wewnętrzne) co oznacza, że ​​DefaultModelBinder nie można ich ustawić (stąd są one null i nie ważne ze względu na atrybuty [Required]. Zmień

public string FirstName { get; internal set; } 

do

public string FirstName { get; set; } 

i to samo ale dla wszystkich innych właściwości z ustawiaczy wewnętrznych.

+0

Boże! i generowane tha t prawdy przez refaktoryzację, nie jestem świadomy, że są wewnętrzni. Przepraszam za te bzdury. Dziękuję bardzo! –

Powiązane problemy