ASP.NET MVC - Populate Commonly Used Dropdownlists

前端 未结 3 465
臣服心动
臣服心动 2020-12-14 23:24

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

相关标签:
3条回答
  • 2020-12-14 23:47

    Custom HTML Helpers is the way to go...

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

    0 讨论(0)
  • 2020-12-14 23:50

    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.

    0 讨论(0)
  • 2020-12-15 00:00

    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>
    
    0 讨论(0)
提交回复
热议问题