My problem is similar to this question 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.
My models are as follows:
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; }
}
My Controller action is:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(UserRegisterViewModel model)
{
if (ModelState.IsValid) //This conditions is false
{
}
return View();
}
It redirects to again register page with the validation error saying Password must match
. Can someone please help ? I have checked this question it helped a bit, but not completely.
If I change the model structure like below, than I get an error saying: Could not find a property named User.Password
:
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; }
}
EDIT
My cshtml page code is like below.
<p>
@Html.LabelFor(model => model.User.Password)
@Html.PasswordFor(model => model.User.Password, new { @class = "wd189 inputtext" })
@Html.ValidationMessageFor(model => model.User.Password)
</p>
<p>
@Html.LabelFor(model => model.CPassword)
@Html.PasswordFor(model => model.CPassword, new { @class = "wd189 inputtext" })
@Html.ValidationMessageFor(model => model.CPassword)
</p>
[Compare("User.Password", ErrorMessage = "Passwords must match")]
is exact problem from the link you've provided (another question). That's why some additional property "Password" was introduced there additionally. – Agat Nov 09 '13 at 19:12