将用户传递给 ViewModel

Pass a user to a ViewModel

好的,有点卡在这里。

VIEWMODEL

public class UserProfileEdit
{
    public virtual ApplicationUser ApplicationUser { get; set; }

    [Required]            
    public string FirstName { get; set; }

    public string TwitterHandle{ get; set; }

    [Required]
    [Display(Name = "Email")]
    [DataType(DataType.EmailAddress)]
    public string Email { get; set; }

    // etc etc
}

控制器

public ActionResult YourProfile()
{
    string username = User.Identity.Name;           

    ApplicationUser user = db.Users.FirstOrDefault(u => u.UserName.Equals(username));

    // Construct the viewmodel
    UserProfileEdit model = new UserProfileEdit();            
   model.ApplicationUser = user;

     return View(model); 
}

在视图上,我在顶部有@model MySite.Models.UserProfileEdit

如何将用户传递给 ViewModel?我知道我可以逐行完成

model.Email = user.Email;

例如,但应该更简单?

您可以逐行进行,也可以使用 AutoMapper。试一试http://automapper.org/

这非常有用,特别是当您在代码中重复使用相同类型的对象映射时。

你有多种选择来做你想做的事。

您可以使用工具,例如 AutoMapper

或者您可以通过构造函数传递数据:

public class UserProfileEdit
    {
        public virtual ApplicationUser ApplicationUser { get; set; }

        [Required]            
        public string FirstName { get; set; }

        public string TwitterHandle{ get; set; }

        [Required]
        [Display(Name = "Email")]
        [DataType(DataType.EmailAddress)]
        public string Email { get; set; }

        // etc etc

        public UserProfileEdit() {}

        public UserProfileEdit(ApplicationUser user) {
              this.ApplicationUser = user;
              this.Email = user.Email;
              // ...
        }

}

 public ActionResult YourProfile()
        {
            string username = User.Identity.Name;           

            ApplicationUser user = db.Users.FirstOrDefault(u => u.UserName.Equals(username));

             return View(new UserProfileEdit(user)); 
        }

或者使用一种方法来初始化视图模型的数据:

public class UserProfileEdit
    {
        public virtual ApplicationUser ApplicationUser { get; set; }

        [Required]            
        public string FirstName { get; set; }

        public string TwitterHandle{ get; set; }

        [Required]
        [Display(Name = "Email")]
        [DataType(DataType.EmailAddress)]
        public string Email { get; set; }

        // etc etc

        public void Init(ApplicationUser user) {
              this.ApplicationUser = user;
              this.Email = user.Email;
              // do what you want to do
        }

}

 public ActionResult YourProfile()
        {
            string username = User.Identity.Name;           

            ApplicationUser user = db.Users.FirstOrDefault(u => u.UserName.Equals(username));
            UserProfileEdit vm = new UserProfileEdit();
            vm.Init(user);

             return View(vm); 
        }