2013-04-23 28 views
0

說我有這些類:如何子對象發送到MVC視圖父對象的列表

public class Animal 
{ 

} 

public class Elephant : Animal 
{ 
    public string Name { get; set; } 
} 

,我有一個控制器的方法

public SubmitElephants() 
{ 
    var elephants = new List<Animal>(); 

    elephants.Add(new Elephant { Name = "Timmy" }; 
    elephants.Add(new Elephant { Name = "Michael" }; 

return View("DisplayElephants", elephants); 

} 

的DisplayElephants看法是這樣的:

@model IList<Elephant> 

@foreach(var elephant in Model) 
{ 
    <div>@elephant.Name</div> 
} 

所以,如果我運行此代碼,我會得到錯誤:

傳遞到字典的模型項的類型爲「System.Collections.Generic.List 1[Animal]', but this dictionary requires a model item of type 'System.Collections.Generic.IList 1 [大象]」

所以,不,我不是想改變我的名單是var elephants = new List<Elephant>();

我我想知道給定的動物列表,我知道只包含大象,我怎麼能從控制器傳遞給大象特定的視圖?

回答

1

AFAIK這是不可能的。從某種意義上說,你所嘗試的與Covariance相反。

This article描述了協方差和逆變。

總之,你可以這樣做 -

IEnumerable<Elephant> elephants = new List<Elephant>(); 
IEnumerable<Animal> animals = elephants; 

你真正想要的其他方式。

另請注意,並非所有通用集合都是協變的。 This article告訴我們在C#中協變的集合。

0

改變這一行:

var elephants = new List<Animal>(); 

到:

var elephants = new List<Elephant>(); 

有關爲什麼是這樣的詳細信息,請參閱@ SRIKANTH的答案。

相關問題