user1082693
user1082693

Reputation: 621

How to create a category list as partial with MVC3

I'm creating a MVC3 web site, and I have place in the page where a dropdown with a list of categories will be rendered, these categories will be pulled from a database and I don't know where/how to put this category list in a way that it can be reused and independent. What I'm doing now is passing the category list as a parameter in my model class with every action being executed.

How can I have it in a way that it will be independent from any action and pull the categories from the database?

thanks!

Upvotes: 2

Views: 156

Answers (1)

Malv20
Malv20

Reputation: 159

In my opinion first you should create partial view with list of categories.

  @Html.DropDownList("Categories", "Choose ...")

In controller you can create an Action where you will get all categories from database

 public PartialViewResult ListOfCategories ()
    {
         ViewBag.Categories = new SelectList(db.Categories, "Id", "Name");

         return PartialView("NameOfYourPartial");     
    }

In Layout file u can execute this function

@{Html.RenderAction("NameOfAction", "YourController");}

And you should have a list of categories in all your views which derive from your layout.

Upvotes: 1

Related Questions