简体   繁体   English

部分视图加载错误的模型

[英]Partial View loading wrong model

I have a partial view in which I have a model specified as such: 我有一个局部视图,其中有一个这样指定的模型:

@model IEnumerable<AbstractThinking2015.Models.BlogModel>

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

And I'm calling this using: 我用这个来称呼它:

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

But I'm getting the error: 但是我得到了错误:

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]'. 传递到字典中的模型项的类型为“ AbstractThinking2015.Models.BlogModel”,但此字典需要模型类型为“ System.Collections.Generic.IEnumerable`1 [AbstractThinking2015.Models.BlogModel]”的模型项。

I'm sure this is because the model being passed into the view is the single blog but I want to use the list that's defined in the partial view. 我确定这是因为传递给视图的模型是单个博客,但是我想使用在局部视图中定义的列表。 Is there a way to do this? 有没有办法做到这一点?

If you do not pass a model t the partial explicitly, It will take the model of the parent view. 如果未显式传递局部模型,它将采用父视图的模型。 So from your error message, It is clear that you are passing a single object of the BlogModel to your view from your action method, hence getting the error. 因此,从您的错误消息中可以很明显地看出,您正在将BlogModel的单个对象从操作方法传递到视图,从而得到了错误。

You need to make sure that your main view (where you are calling the partial), is also strongly typed to a collection of BlogModel objects. 您需要确保您的主视图(您在其中调用局部视图)也被强类型BlogModel对象的集合。

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

  return View(blogList);
}

And the Index view, where you are calling the Partial will be strongly typed to a collection of BlogModel . 并且在其中调用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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM