c# - 将用户传递给 ViewModel

标签 c# asp.net-mvc viewmodel

好吧,有点卡在这里。

View 模型

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

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

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

model.Email = user.Email;

举个例子,但是应该更简单吧?

最佳答案

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

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

关于c# - 将用户传递给 ViewModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37429014/

相关文章:

javascript - 无法看到警报 - mvc5 通过 TempData 进行引导

javascript - MVC Bootstrap 部分 View ValidationMessageFor 在加载页面时执行

android - 如何在kotlin fragment 类的 View 模型中调用接口(interface)方法

asp.net - ASP.NET MVC 中用于读取、创建和更新操作的单独 ViewModel

javascript - 将 Razor 代码分配给 JavaScript 变量时出现意外标记非法

android - 将数据从 Viewmodel 设置为 Activity android kotlin

c# - 扩展 Bootstrap 选择

c# - 如何将通过反射获得的对象传递给模板?

c# - 如何在 C# 中从 MS office 文档中提取文本

.net - 将 jEditable 与 ASP.NET MVC 结合使用(POST)