Reputation: 4067
Getting a model error when using MVC4 Compare attribute against a nested property.
Error is as follows Could not find a property named PASSWORD
.
What is the correct way to use Compare for Nested Property comparison?
User.cs
public partial class User
{
public User()
{
this.Mobilizations = new HashSet<Mobilization>();
}
[Required(ErrorMessage="Password is required")]
[DataType(DataType.Password)]
public string PASSWORD { get; set; }
}
UserViewModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using CompareAttribute = System.Web.Mvc.CompareAttribute;
public class userViewModel
{
public User User { get; set; }
[DataType(DataType.Password)]
[Required(ErrorMessage = "CONFIRM PASSWORD is required")]
[Display(Name="CONFIRM PASSWORD")]
[CompareAttribute("PASSWORD",ErrorMessage="Password didnot match")]
public string ComparePassword { get; set; }
public IEnumerable<Designation> DesignationList { get; set; }
public SelectList MenuList { get; set; }
[Required(ErrorMessage="Select some menu items")]
public string[] MenuIds { get; set; }
}
Controller
[HttpPost]
public ActionResult Create(userViewModel model)
{
if (ModelState.IsValid) //<= **Getting Model error here**
{
_db.Entry(model.User).State = EntityState.Modified;
_db.SaveChanges();
}
return RedirectToAction("Create");
}
The View is as follows
<div class="form-group">
@Html.LabelFor(model => model.User.PASSWORD, new { @class = "col-sm-2 control-label " })
<div class="col-sm-6 ">
@Html.EditorFor(model => model.User.PASSWORD, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.User.PASSWORD)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.ComparePassword, new { @class = "col-sm-2 control-label " })
<div class="col-sm-6 ">
@Html.EditorFor(model => model.ComparePassword, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.ComparePassword)
</div>
</div>
How can i solve this issue?
Upvotes: 0
Views: 662
Reputation: 1058
Try like this:
[CompareAttribute("User.Password", ErrorMessage="Password didnot match")]
public string ComparePassword { get; set; }
Or, remove the User property from your ViewModel and add
public string Password {get; set;}
[CompareAttribute("Password", ErrorMessage="Password didnot match")]
public string CinfirmPassword {get; set;}
Later you can populate your User object.
And here you can find a workaround.
Upvotes: 1