使用自定义模型编辑时出现问题

时间:2011-09-08 09:19:22

标签: asp.net-mvc asp.net-mvc-3 viewmodel

我有这个数据模型:

public class User
    {
        public long UserID { get; set; }

        [Required(ErrorMessage = "User name is required.")]
        [MaxLength(50, ErrorMessage = "User name cannot be longer than 50 characters.")]
        public string UserName { get; set; }

        [Email]
        [Required(ErrorMessage = "Email is required.")]        
        [MaxLength(100, ErrorMessage = "Email cannot be longer than 100 characters.")]
        public string Email { get; set; }

        [Required(ErrorMessage = "Password is required.")]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]        
        public string Password { get; set; }

        [MaxLength(150, ErrorMessage = "Full name cannot be longer than 150 characters.")]
        public string FullName { get; set; }

        public int UserTypeID { get; set; }

        public virtual UserType UserType { get; set; }
        public virtual ICollection<Page> Pages { get; set; }
    }

我正在使用此模型仅编辑某些字段(密码不可编辑):

public class EditUserModel
    {
        public long UserID { get; set; }

        [Required]
        [Display(Name = "User name")]
        public string UserName { get; set; }

        [Email]
        [Required(ErrorMessage = "Email is required.")]
        [MaxLength(100, ErrorMessage = "Email cannot be longer than 100 characters.")]
        public string Email { get; set; }

        [DataType(DataType.Text)]
        [Display(Name = "Full name")]
        [MaxLength(150, ErrorMessage = "Full name cannot be longer than 150 characters.")]
        public string FullName { get; set; }

        public int UserTypeID { get; set; }

        public virtual UserType UserType { get; set; }
    }

但我对如何将EditUserModel传递给我的数据上下文以更新它感到困惑。对不起,如果看起来很简单,但我真的很难过。

这是我修改过的自动生成的编辑操作:

[IsAdministrator]
[HttpPost]
        public ActionResult Edit(EditUserModel user)
        {
            if (ModelState.IsValid)
            {
                db.Entry(user).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.UserTypeID = new SelectList(db.UserTypes, "UserTypeId", "Name", user.UserTypeID);
            return View(user);
        }

这是我遇到的问题:

db.Entry(user).State = EntityState.Modified;

我创建自定义类的原因是为了避免从视图中泄露密码。

1 个答案:

答案 0 :(得分:1)

这不起作用,因为您正在尝试保存视图模型。

您可以使用AutoMapper将视图模型中的数据重写到数据模型中。之后,您应该能够保存更改。

User userModel = Mapper.Map<EditUserModel, User>(user);
userModel = // todo: get password from database
// todo: attach your model to context and save changes

我正在使用Entity Framework Code First,这种方法效果很好。