简体   繁体   中英

ASP.NET MVC - Populate Commonly Used Dropdownlists

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

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM