Rocshy
Rocshy

Reputation: 3509

Partial View different model

I am trying to use a partial view that uses a different model than the one used in the main view. The partial view has to show a list with the products recently added. But I am stuck on how and where to implement the logic for retrieving the data I need from the database.

Home/Index.cshtml:

@Html.Partial("~/Views/Shared/_LatestProducts.cshtml", new List<Website.Models.LatestProductsList>())


Shared/_LatestProducts.cshtml:

@model List<Website.Models.LatestProductsList>

@foreach (var item in Model)
{
    <a href="#" title="img">
    <img src="~/Content/images/latest-product-img.jpg" alt="" /><p>@item.ProductName</p>
    </a>
}

And I have the following code that I am trying to use in order to get some products for tests and show them in the partial view:

public PartialViewResult _LatestProducts()
{
    List<LatestProductsList> latestProd = (from p in db.Products
                                           where p.ID < 5
                                           select new LatestProductsList { ProductName = p.Title }).ToList();

    return PartialView(latestProd);
}

I thought that I might use it in the HomeController, but that obviously doesn't work and I am not sure if partial views should have their own controller, if I can just call it from another class. I am still wrapping my head around ASP MVC, so any help will be appreciate it.

Upvotes: 2

Views: 384

Answers (1)

Ufuk Hacıoğulları
Ufuk Hacıoğulları

Reputation: 38468

Just call the action that renders the partial view in Index.cshtml.

@Html.Action("_LatestProducts", "Product")

Second parameter is the name of the controller that has the _LatestProducts method.


Just a reminder: Names with _ prefix is for partial views only, not action methods. You should rename it to LatestProducts.

Upvotes: 3

Related Questions