2012-07-20 58 views
2

我正在學習C#ASP.NET MVC 3中的ViewModels,並且我被困在從ViewModel顯示數據的視圖中。ASP.NET MVC3 ViewModel - 困惑

模式

public class Author 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public virtual ICollection<Book> Books { get; set; } 
} 

public class Book 
{ 
    public int Id { get; set; } 
    public int AuthorId { get; set; } 
    public string Title { get; set; } 
    public decimal Price { get; set; } 
} 

在我的索引視圖我想告訴作者和書籍的一般列表。我已經做了視圖模型此:

public class BookIndexViewModel 
{ 
    public List<Book> Books { get; set; } 
    public List<Author> Authors { get; set; } 
} 

這裏是我的指數()操作方法從控制器:

public ViewResult Index() 
    { 
     BookIndexViewModel viewModel = new BookIndexViewModel(); 
     viewModel.Authors = db.Authors.ToList(); 

     // leaving Books empty for now 

     return View(viewModel);   
    } 

我有一個強類型索引視圖,我想顯示作者列表:

@model IEnumerable<NewBookStore.ViewModels.BookIndexViewModel> 

@foreach (var author in Model.Authors) { 
<tr> 
    <td> 
     @author.Name 
    </td> 
</tr> 
} 

這是Model.Authors不起作用的部分。當我鍵入模型。並等待智能感知顯示作者,它沒有列出。錯誤說明是:

「System.Collections.Generic.IEnumerable」不包含關於'作者的定義,並沒有擴展方法「作者的接受型的第一參數「System.Collections.Generic.IEnumerable '可以找到(是否缺少using指令或程序集引用?)

+1

視圖中的模型不應該是IEnumerable。您正在發送一個包含2個列表的單個模型。您沒有發送視圖模型列表。 – keshav 2012-07-20 15:52:38

回答

2

視圖中的模型不應該是IEnumerable。您正在發送一個包含2個列表的單個模型。您沒有發送視圖模型列表。

+2

謝謝,我不相信這個解決方案如此簡單。總是發生! :) – 502502 2012-07-20 16:09:34

+1

沒問題:)它總是這些小事情你最終花費最多的時間 – keshav 2012-07-20 16:18:39

0

@model IEnumerable<NewBookStore.ViewModels.BookIndexViewModel>應該 @model BookIndexViewModel而不是!

您不希望IEnumerableBookIndexViewModel - 作者屬性直接關閉您的BookIndexViewModel

乾杯, 院長

0

因爲你不是一個合格的collection查看,你是從你的操作方法傳遞BookIndexViewModel類只有一個對象。

要解決這個問題,更新您的視圖將其綁定到只有一個實例,而不是collection

@model NewBookStore.ViewModels.BookIndexViewModel 

@foreach (var author in Model.Authors) 
{ 
<tr> 
    <td> 
     @author.Name 
    </td> 
</tr> 
} 
0

Finnayra的,

你這裏的錯誤是你沒有正確定義模型。您的模型已經擁有IEnumerable集合,因此不需要將其設置爲Enumerable。請嘗試:

@model NewBookStore.ViewModels.BookIndexViewModel 
0

使用這個代替

@model NewBookStore.ViewModels.BookIndexViewModel 
0

[注 - 我沒有足夠的經驗,使這不是一個答案評論!]

我閱讀關於的ViewModels從什麼@Darin季米特洛夫說的話是,你應該避免將域對象到您的視圖模型的另一篇文章,

「查看模型不應該引用任何服務。查看模型不應引用任何域模型「。

看看 - > ASP.NET MVC 3 Viewmodel Pattern

我知道的模式更像是不適合所有情況,但像OP,我需要顯示域對象的列表(圖書和作者,我們只想說,指南),所以在OP的例子,應該在ViewModel有?:

public class BookIndexViewModel 
{ 
    public IEnumerable<SelectListItem> Books { get; set; } 
    public IEnumerable<SelectListItem> Authors { get; set; }  
}  

的BookIndexViewModel然後在您的控制器填充(可能使用服務來獲取圖書的清單和作者的列表,以拉平到視圖模型) ??

我也在學習這個東西,所以建議/意見和更正開放!謝謝。