2015-03-09 5 views
0

Получение ошибки модели при использовании MVC4 Сравнивать атрибут с вложенным свойством.MVC4 Свойства атрибута и вложенных объектов MVC4

Ошибка следующая Could not find a property named PASSWORD.

Каков правильный способ сравнения Compare для сравнения Nested Property?

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

Контроллер

[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 выглядит следующим образом

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

Как я могу решить эту проблему?

+0

Не должно быть запятой User.Password в кавычках – ksg

ответ

1

Попробуйте так:

[CompareAttribute("User.Password", ErrorMessage="Password didnot match")] 
public string ComparePassword { get; set; } 

Или удалить свойство пользователя из вашей ViewModel и добавить

public string Password {get; set;} 

[CompareAttribute("Password", ErrorMessage="Password didnot match")] 
public string CinfirmPassword {get; set;} 

Позже вы можете заполнить ваш объект пользователя.

И here вы можете найти обходное решение.

Смежные вопросы