Reputation: 67203
I'm new to ASP.NET MVC and I have a partial view with a combo box, which I need to dynamically populate.
My understanding is that I can put the list data in the ViewBag for the view, and it will be available from my partial view.
However, I want to be able to use the partial view from several different pages. Must all pages that use the partial view populate ViewBag with the list data? Is there any way to encapsulate this within my partial view?
Upvotes: 1
Views: 1046
Reputation: 4770
You can use a child action for this.
Make an action in a controller that just sets the ViewBag and returns the combo box partial view.
e.g.
[ChildActionOnly]
public ActionResult MyDropDown()
{
ViewBag.DropDown = blah;
return PartialView();
}
Then, any view that needs to use that dropdown list renders it as a child action.
e.g.
@{ Html.RenderAction("MyDropDown", "MyController"); }
Upvotes: 1
Reputation: 423
Look at this question: ViewModel Best Practices. May be you should create a base view model containing the list data and (if needed) inherit other view models from it.
For instance:
class ViewModelWithFooList
{
public List<Foo> FooList
{
get { return new List<Foo>() { new Foo("one"), new Foo("two"), new Foo("three") }; }
}
}
You can inherit other view models from ViewModelWithFooList if you need to.
In controller:
public ActionResult GetList()
{
return View(new ViewModelWithFooList());
}
And in your views:
@Html.RenderPartial("FooList", Model.FooList);
Views and partial view "FooList" must be strongly typed.
Upvotes: 1
Reputation: 60486
You should pass data to your partial View using
@Html.Partial("", yourData)
and access them in your partial view using
@ViewData.Model
Upvotes: 1