将用户传递给ViewModel

时间:2016-05-25 06:07:55

标签: c# asp.net-mvc 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
}

CONTROLLER

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;
例如

,但它应该更简单?

2 个答案:

答案 0 :(得分:3)

您可以逐行执行此操作,也可以使用AutoMapper。试一试http://automapper.org/

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

答案 1 :(得分:2)

您有多种选择可以做您想做的事。

您可以使用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); 
        }