MVC Partial View with List Model

1.9k views Asked by At

I have a news item page and I would like to include a partial view presenting a list of the latest 5 news items. However, I get a

this dictionary requires a model item of type 'System.Collections.Generic.List

error message. I'm assuming the main view is strong typed to present a single item, whereas the partial view is strongly typed with a generic list and the two don't match.

Controller

public ActionResult NewsItem(int newsId, string newsTitle)
{
    var q = _ctx.tblNews.Single(x => x.newsID == newsId);

    return View(q);
}

public ActionResult NewsLatest()
{
    var q = _ctx.tblNews.OrderBy(x => x.newsCreateDate)
            .Where(x => x.WebsiteID == 2 && x.newsPublish).Take(5).ToList();
    return View(q);
}

View (simplified)

@using MyMVC.Models
@model tblNews

<h2>@Model.newsTitle</h2>
@Html.Raw(Model.newsText)
<p>@Model.newsCreateDate</p>
@Html.RenderPartial("NewsLatest")

Partial View

@using MyMVC.Helpers
@model List<MyMVC.Models.tblNews>

<table>
    @foreach (var x in Model)
    {
        <tr>
            <td>
                @Html.ActionLink(x.newsTitle, "NewsItem", new { newsId = x.newsID, newsTitle = x.newsTitle.ToSeoUrl() })<br />
                <hr />
            </td>
        </tr>
    }
</table>

I tried this in the view:

@{
    Html.RenderPartial("NewsLatest", new List<tblNews> { new tblNews()});
}

but it looks like the ActionResult doesn't get fired trying i this way.

There are a few questions on SO relating to this. But I just can't get my head around the solutions. The penny isn't dropping!

Do I really have to create a view model that incorporates the news item data and the list of news items?

0

There are 0 answers