Sidriel
Sidriel

Reputation: 27

Adding a Categorylist to all pages with MVC4

I'm new with MVC4 and just MVC.

I have a homecontroller and a categorycontroller. The categorycontroller sends data from the model to the categoryIndex view. That's works fine.

But now I want to add the categorylist on all the available controllers.

I already fixed this to add in all classes return view(db.categorys.ToList()); and add categoryIndex to the shared folder. In _layout.cshtml I'm adding a@RenderPage("~/")` and this works.

But when I have to pass more than only the (db.categorys.ToList()) in the return it goes wrong.

How can I fixed this problem. How do I add the categorylist too every controller and page properly?

Upvotes: 1

Views: 180

Answers (2)

Shyju
Shyju

Reputation: 218752

Add CategoryList collection as a property to your ViewModels( of all pages). You can add that to a base class and inherit from that also.

public class Category
{
  public int ID { set;get;}
  public string Name { set;get;}
}
public class BasePageViewModel
{
  public List<Category> CategoryList { set;get;}

  BasePageViewModel()
  {
    CategoryList=new List<Category>();
  }
}

Now you can inherit from this base class for other view models.

public class ProductViewModel : BasePageViewModel
{
  public string ProductName { set;get;}
  //Other properties
}

Now in your view, which is strongly typed to ProductViewModel, you can call Html.Partial to show the CategoryList partial view.

@model ProductViewModel
<h3>This page is for product @Model.ProductName</h3>
@Html.Partial(Model.CategoryList)

Assuming you have a partial view to render the CategoryList

Upvotes: 1

DeeDub
DeeDub

Reputation: 1662

I would suggest throwing commonly used things, such as a category list, into the ViewBag. This will allow you some separation and only returning to the view what needs to be there. Hope this helped!

Upvotes: 0

Related Questions