[英]MVC 4 Passing Data To Partial View - Format
我無法理解MVC4中的部分視圖。 我目前有一個“用戶配置文件”頁面,我希望有一個局部視圖來顯示另一個包含其UserID的表中的每個記錄。
這是我用來在控制器中調用函數的HTML幫助器。
@Html.Action("DisplayArticles", "Articles")
這是我在“文章”控制器中調用的用於顯示用戶文章的方法。
[HttpGet]
[ChildActionOnly]
public ActionResult DisplayArticles()
{
int id = WebSecurity.CurrentUserId;
var articleList = new List<Article>();
//Article articles = (from j in db.Article
// where j.UserID == id
// select j).ToList();
//articleList.AddRange(articles);
foreach (Article i in db.Article)
{
if (i.UserID == id)
{
articleList.Add(i);
}
}
return PartialView("_DisplayWritersArticle", articleList);
}
我的局部視圖_DisplayWriterArticle僅使用HTML幫助器來顯示數據。
@model Writegeist.Models.Article
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.UserID)
</th>
<th>
@Html.DisplayNameFor(model => model.Title)
</th>
<th>
@Html.DisplayNameFor(model => model.Type)
</th>
<th>
@Html.DisplayNameFor(model => model.Content)
</th>
</tr>
<tr>
<th>
@Html.DisplayFor(model => model.UserID)
</th>
<td>
@Html.DisplayFor(model => model.Title)
</td>
<td>
@Html.DisplayFor(model => model.Type)
</td>
<td>
@Html.DisplayFor(model => model.Content)
</td>
</tr>
</table>
我的問題是我將列表傳遞到視圖中的方式,它沒有被識別並且出現了錯誤
> The model item passed into the dictionary is of type
> 'System.Collections.Generic.List`1[Writegeist.Models.Article]', but
> this dictionary requires a model item of type
> 'Writegeist.Models.Article'.
如果我改變
return PartialView("_DisplayWritersArticle", articleList);
至
return PartialView("_DisplayWritersArticle", new Writegeist.Models.Article());
我認為articleList的格式不正確。 誰能指出我正確的方向? 謝謝
您的“部分視圖”期望只有一篇文章,您將為其提供清單。
將模型更改為文章列表:
@model List<Writegeist.Models.Article>
然后,您必須遍歷列表以顯示所有內容:
<table>
@foreach(Article article in Model) {
<tr>
<th>
@Html.DisplayNameFor(a => article.UserID)
</th>
<th>
@Html.DisplayNameFor(a => article.Title)
</th>
<th>
@Html.DisplayNameFor(a => article.Type)
</th>
<th>
@Html.DisplayNameFor(a => article.Content)
</th>
</tr>
}
</table>
問題是,正如我看到的那樣,您正在傳遞列表,但是您告訴視圖它只是一篇文章。
改變你的
@model Writegeist.Models.Article to @model List<Writegeist.Models.Article>
然后,您將需要遍歷該列表以獲取所需的數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.