title: ASP.NET MVC 4 validation on complex models - model does not validated on server side
body: <p>My problem is similar to <a href="https://stackoverflow.com/questions/18087358/asp-net-mvc-4-unobtrusive-validation-broken-on-complex-models">this question</a> but I'm still having problem with validation both server- and client-side. I want to perform a compare on two properties, set in different models.</p>
  
  <p>My models are as follows:</p>
  
  <pre><code>public class User{
    public string Password { get; set; }
  }
  
  public class UserRegisterViewModel {
      public User User{ get; set; }
  
      //This is suggested in linked question - as Compare can only work with local property
      public string Password 
      {
          get{return this.User.Password;}
      }
  
      [DataType(DataType.Password)]
      [Compare("Password", ErrorMessage = "Passwords must match")]
      [Required(ErrorMessage = "Confirm password is required")]
      [DisplayName("Confirm Password")]
      public string CPassword { get; set; }
  }
  </code></pre>
  
  <p>My Controller action is:</p>
  
  <pre><code>[HttpPost]
  [AllowAnonymous]
  [ValidateAntiForgeryToken]
  public ActionResult Register(UserRegisterViewModel model)
  {
      if (ModelState.IsValid) //This conditions is false
      {
      }
      return View(); 
  }
  </code></pre>
  
  <p>It redirects to again register page with the validation error saying <code>Password must match</code>. Can someone please help ? I have checked <a href="https://stackoverflow.com/questions/18087358/asp-net-mvc-4-unobtrusive-validation-broken-on-complex-models">this question</a> it helped a bit, but not completely.</p>
  
  <p>If I change the model structure like below, than I get an error saying: <code>Could not find a property named User.Password</code>:</p>
  
  <pre><code>public class UserRegisterViewModel {
      public User User{ get; set; }
  
      [DataType(DataType.Password)]
      [Compare("User.Password", ErrorMessage = "Passwords must match")]
      [Required(ErrorMessage = "Confirm password is required")]
      [DisplayName("Confirm Password")]
      public string CPassword { get; set; }
  }
  </code></pre>
  
  <p><strong>EDIT</strong></p>
  
  <p>My cshtml page code is like below.</p>
  
  <pre><code>&lt;p&gt;
      @Html.LabelFor(model =&gt; model.User.Password)
      @Html.PasswordFor(model =&gt; model.User.Password, new { @class = "wd189 inputtext" })
      @Html.ValidationMessageFor(model =&gt; model.User.Password)
  &lt;/p&gt;
  &lt;p&gt;
      @Html.LabelFor(model =&gt; model.CPassword)
      @Html.PasswordFor(model =&gt; model.CPassword, new { @class = "wd189 inputtext" })
      @Html.ValidationMessageFor(model =&gt; model.CPassword)
  &lt;/p&gt;
  </code></pre>