【问题标题】:Partial View loading wrong model局部视图加载错误的模型
【发布时间】:2016-01-08 10:48:30
【问题描述】:

我有一个局部视图,其中我有一个这样指定的模型:

@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>

但我得到了错误:

传入字典的模型项是类型 'AbstractThinking2015.Models.BlogModel',但是这本词典需要 类型的模型项目 'System.Collections.Generic.IEnumerable`1[AbstractThinking2015.Models.BlogModel]'。

我确定这是因为传递到视图中的模型是单个博客,但我想使用部分视图中定义的列表。有没有办法做到这一点?

【问题讨论】:

  • 你的主视图渲染是什么?
  • 目前它刚刚崩溃,但它使用的模型是:@model AbstractThinking2015.Models.BlogModel

标签: c# asp.net-mvc


【解决方案1】:

如果你没有显式地传递一个模型,它将采用父视图的模型。因此,从您的错误消息来看,很明显您正在将 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);
}

您在其中调用 Partial 的 Index 视图将被强类型化为 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>

【讨论】:

  • 虽然这是正确的解释,但 OP 可能正在寻找类似 @​​987654325@ 的内容,而不是将当前帖子呈现为最近帖子的列表。
  • 我同意他应该有一个视图模型,该模型具有最近的帖子属性,他应该将其传递给部分。从他的原始帖子来看,尚不清楚他试图用索引视图做什么。所以我不知道他真正应该为他的索引视图使用什么视图模型!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多