Carlos M.
Carlos M.

Reputation: 15

Best Practice to call different lists

Now I'm calling object into _Layout menu with PartialView like these:

Controller:

public async Task<ActionResult> GetChemicalsList()
{
    var model = db.ProductsList.Where(x => x.Subcategory.Name == "Chemicals").ToList();
    return PartialView(@"~/Views/Product/_ChemicalPartialView.cshtml", model);
} 

Partial View:

@model IEnumerable<Product>

@foreach (var item in Model)
{
    <a href="@Url.Action("Index", "Product", new { id= item.ProductId})">@Html.DisplayFor(modelItem => item.Name)</a>
}

Layout View:

<div class="col-xs-6 col-sm-2">
    @Html.Action("GetChemicalsList", "Product")
</div>

But I have another products with different subcategory to add, so I need to do a controller and different call into View for each one because each one have a different query on controller: for example, I do another one for accessories, so my controller be like these one:

Accessories controller:

public async Task<ActionResult> GetAccesoriesList()
{
    var model = db.ProductsList.Where(x => x.Subcategory.Name == "Accesories").ToList(); // diferent Query
    return PartialView(@"~/Views/Product/_ChemicalPartialView.cshtml", model);
} 

_Layout View

<div class="col-xs-6 col-sm-2">
   @Html.Action("GetAccesoriesList", "Product")
</div>

Is the correct way to do that, or there another best way?

Thanks in advance!

Upvotes: 1

Views: 43

Answers (1)

Bon Macalindong
Bon Macalindong

Reputation: 1320

You can create a generic Action that will return your list depending on what sub category you want. Then you pass it from the view to controller as route data.

Controller:

public async Task<ActionResult> GetSubCategoryList(string subCategory)
{
    var model = db.ProductsList.Where(x => x.Subcategory.Name == subCategory).ToList(); 
    return PartialView(@"~/Views/Product/_ChemicalPartialView.cshtml", model);
} 

View:

@Html.Action("GetSubCategoryList", "Product", new { subCategory = "Accessories" })

You may need to change your route config to match this route.

Upvotes: 1

Related Questions