MVC4比较属性和嵌套对象属性

时间:2015-03-09 15:03:08

标签: asp.net-mvc-4 model compare

使用MVC4比较属性与嵌套属性时出现模型错误。

错误如下Could not find a property named PASSWORD

使用比较进行嵌套属性比较的正确方法是什么?

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

视图如下

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

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

试试这样:

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

或者,从ViewModel中删除User属性并添加

public string Password {get; set;}

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

稍后您可以填充您的User对象。

here您可以找到解决方法。