ufukcalimli ufukcalimli - 21 days ago 5
C# Question

Error with partial view

I am working in blog web site project. I create partial view for blog post.

İt's _MainContent partial view

@model System.Collections.Generic.IEnumerable<Blog.Data.Model.Article>

@foreach (var item in Model)
{
<div class="panel">
<div class="panel-body">
<div>
<h3>
@Html.ActionLink(item.ArticleTitle, "Index", "Article", new { id = item.ArticleId }, new { })
</h3>
</div>
<div id="img">
<img width="400" height="300" src="@string.Format("data:{0};base64,{1}",item.ArticleImages.FirstOrDefault().ContentType,Convert.ToBase64String(item.ArticleImages.FirstOrDefault().Content))" />
</div>
<div>
<p>
@Html.DisplayFor(x=> item.Content)
</p>
</div>

</div>
</div>
}


And it's Index page

@model System.Collections.Generic.IEnumerable<Blog.Data.Model.Article>
@{
ViewBag.Title = "Anasayfa";
}

<div class="container">
<div class="col-md-offset-10 col-md-2">
@Html.Partial("_SideMenuPartial")
</div>

<div class="col-md-10">
@Html.Partial("_MainContent", Model.FirstOrDefault())
</div>
</div>


When i started this program then happen

An exception of type 'System.InvalidOperationException' occurred in System.Web.Mvc.dll but was not handled in user code

Additional information: The model item passed into the dictionary is of type 'System.Data.Entity.DynamicProxies.Article_E29CF5FDD5B2D2829B35531643263744339081C99736858CE61DDB0981D557EE', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[Blog.Data.Model.Article]'.


And i have a empty page.

Answer

The view is expecting a collection of Article objects:

@model System.Collections.Generic.IEnumerable<Blog.Data.Model.Article>

You're passing it a single Article object:

@Html.Partial("_MainContent", Model.FirstOrDefault())

Instead, provide the view with the collection that it's expecting:

@Html.Partial("_MainContent", Model)

(or any subset of that collection, but still an IEnumerable<Article>)