2014-04-09 49 views
1

我有一個簡單的聯繫人列表應用程序。我正在使用與我的域模型完全分離的視圖模型。查看具有的IEnumerable這裏是我的指數()action方法來呈現列表:ASP.Net MVC傳遞列表<>使用IEnumerable <>查看

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

有沒有辦法用更少的代碼來完成呢?

回答

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

當然,使用AutoMapper

安裝完成後,首先創建一個新的映射。你只需要做一次,我個人在Application_Start

Mapper.CreateMap<Contact, ContactListVM>(); 

然後,它就像將查詢結果映射到所需輸出一樣簡單。

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

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

你完成了,那很簡單。

相關問題