ASP.Net MVC传递列表<>使用IEnumerable<>进行查看

时间:2014-04-09 20:01:36

标签: asp.net-mvc

我有一个简单的联系人列表应用程序。我正在使用与我的域模型完全分离的视图模型。 View有IEnumerable这是我的Index()Action方法来呈现List:

private AddressBookContext db = new AddressBookContext();

public ActionResult Index()
{
    List<ContactListVM> viewListVM = new List<ContactListVM>();
    foreach (Contact c in db.Contacts.ToList())
    {
        viewListVM.Add(new ContactListVM
        {
            ContactID = c.ContactID,
            FirstName = c.FirstName,
            LastName  = c.LastName,
            Address1  = c.Address1,
            Address2  = c.Address2,
            City      = c.City,
            State     = c.State,
            ZipCode   = c.ZipCode,
            Phone     = c.Phone,
            Email     = c.Email,
            BirthDate = c.BirthDate         
        });
    }
    return View(viewListVM);
}

有没有办法用更少的代码来实现这个目标?

2 个答案:

答案 0 :(得分:0)

Automapper是一个Nuget包,可以帮助您清理代码。具体来说,它将无需手动将您的域属性分配给您的viewmodel属性。

涉及一些设置,但最终结果如下:

public ActionResult Index()
{
    List<ContactListVM> viewListVM = new List<ContactListVM>();
    foreach (Contact c in db.Contacts.ToList())
    {
        viewListVM.Add(Mapper.Map<Contact, ContactListVM>(c));
    }
    return View(viewListVM);
}

答案 1 :(得分:0)

当然,使用AutoMapper

安装完成后,首先创建一个新映射。您只需要执行一次此操作,我个人在Application_Start中执行此操作。

Mapper.CreateMap<Contact, ContactListVM>();

然后就像将查询结果映射到所需的输出一样简单。

public ActionResult Index()
{
    var contacts = db.Contacts.ToList();

    return View(Mapper.Map<List<ContactListVM>>(contacts));
}

你完成了,就这么简单。