11

I was wondering what the best practice is when populating commonly used dropdownlists in ASP.NET MVC. For instance, I have a Country and State select which is used often in my application. It seems dirty to populate viewmodel and bind to that viewmodel from my controller for every single view I want to contain such a dropdownlist.

How do people populate their dropdownlists in such cases? - custom baseclass with this baked in? Helper classes, etc?

Thanks in advance,

JP

JP.
  • 5,536
  • 7
  • 58
  • 100

3 Answers3

8

You can have a RequiresStateList attribute to inject that common functionality to the actions that need it.

public class RequiresStateList : ActionFilterAttribute {
    public override void OnResultExecuting(ResultExecutingContext filterContext) 
    {
        filterContext.Controller.ViewData["StateList"] = GetStates();
    }
}

And your action

[RequiresStateList]
public ActionResult Index() {
    return View();
}

Now you can get that list from the ViewData in your view.

Çağdaş Tekin
  • 16,592
  • 4
  • 49
  • 58
3

Custom HTML Helpers is the way to go...

http://www.asp.net/mvc/tutorials/creating-custom-html-helpers-cs

WayneC
  • 2,530
  • 3
  • 31
  • 44
  • Very elegant: Neither the model nor the view are bloated. The *code* in the view is elegant and reusable. The HtmlHelper can be separately unit tested. – Serge Wautier Feb 11 '11 at 12:17
  • I like this solution over having them in the models. I prefer to keep my models to the data that is being populated/submitted, which in this case, would be the selected value -- not the complete list of values. These also come in handy to allow your view templates to fetch the `Text` property of a selected value for DispalyFor templates (i.e. fetch me the Text property where Value property matches the selected value). – Jerad Rose Oct 24 '11 at 18:50
  • Extending HTML Helpers with DAL breaks MVC architecture, because you will be having your views calling to the data layer instead of it just being a dummy. Though breaking MVC architecture is not necessarily a bad thing. – Yorro Jul 11 '13 at 12:06
0

I'm a big fan of creating view models that match (model) each view exactly. So if you have a view with a States dropdown list, my view model for that page would have a States collection of ListItems.

I wouldn't worry about having view models with a states collection on it. Instead I'd centralize the logic to get the states, something like:

viewModel.States = StatesHelper.GetStates(); // returns IList<ListItem>
MrDustpan
  • 5,508
  • 6
  • 34
  • 39
  • there is an interesting argument about this approach here: http://mikehadlow.blogspot.com/2010/10/populating-drop-down-lists-in-aspnet.html – Merritt Feb 25 '11 at 16:44