2016-01-08 33 views
0

我有,我有一個模型指定爲這樣的局部視圖:局部視圖加載錯誤的模型

@model IEnumerable<AbstractThinking2015.Models.BlogModel> 

@foreach (var item in Model.Take(5)) 
{ 
    <li>@Html.ActionLink(item.Title, "Details", new { id = item.BlogModelId })</li> 
} 

我打電話這一點使用:

<div class="widget"> 
    <h4>Recent Posts</h4> 
    <ul> 
     @Html.Partial("View") 
    </ul> 
</div> 

但我發現了錯誤:

The model item passed into the dictionary is of type 'AbstractThinking2015.Models.BlogModel', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[AbstractThinking2015.Models.BlogModel]'.

我敢肯定,這是因爲該模型被傳遞到視圖是一個博客,但我想用在部分視圖中定義的列表。有沒有辦法做到這一點?

+0

你的主視圖渲染是什麼? – Shyju

+0

目前它只是打破,但它使用的模型是:@model AbstractThinking2015.Models.BlogModel –

回答

4

如果您沒有明確傳遞模型t部分,它將採用父視圖的模型。所以從你的錯誤信息,很明顯你是從你的操作方法傳遞一個BlogModel對象到你的視圖,因此得到錯誤。

您需要確保您的主視圖(您稱之爲部分),也強烈鍵入到BlogModel對象的集合中。

public ActionResult Index() 
{ 
    var blogList=new List<Models.BlogModel>(); 
    // or you may read from db and load the blogList variable 

    return View(blogList); 
} 

和索引視圖,您撥打的部分將被強類型到BlogModel集合。

@model List<Models.BlogModel> 
<h1>Index page which will call Partial</h1> 
<div class="widget"> 
    <h4>Recent Posts</h4> 
    <ul> 
     @Html.Partial("View") 
    </ul> 
</div> 
+0

雖然這是正確的解釋OP可能尋找像'@ Html.Partial(「View」,Model.RecentPosts)'而不是將當前帖子呈現爲近期帖子的列表。 –

+0

我同意他應該有一個具有RecentPosts屬性的視圖模型,他應該傳遞給部分。從他原來的文章來看,他不清楚他想用索引視圖做什麼。所以我不知道他真的應該爲他的索引視圖使用什麼視圖模型! – Shyju