All my controllers in my project inherit from a base controller, which has a property with my Entity Model.
Let say I have a view that shows cities in the world, and it has an option to filter by country. The country filter is a dropdown list of countries from the database. The Html helper for the dropdown list requests a IEnumerable<SelectItem>.
Now with that info, is it ok if I create a HtmlHelper that looks like this:
public static IEnumerable<SelectListItem> GetCountries(HtmlHelper htmlHelper)
{
return (from c in ((BaseController) htmlHelper.ViewContext.Controller).Entities.Countries
orderby c.Name
select new SelectListItem() {Text = c.Name, Value = c.ID});
}
The question is not if I it is possible, but if it is ok according to the MVC way of doing things. (Or should I put the collection of countries in the ViewData inside the controller?)
I would pass the data as a parameter to the GetCountries method. The htmlHelper function really shouldn’t know about the properties of your base controller – what if someone were to ever use it on a controller that doesn’t inherit from your base? I know I know, you control the code, blah blah. If you’re really interested in best practices, avoid the dependency.
then, in your View: