Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 809
JP. Avatar asked Nov 20 '10 04:11

JP.


2 Answers

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.

like image 84
Çağdaş Tekin Avatar answered Oct 07 '22 14:10

Çağdaş Tekin


Custom HTML Helpers is the way to go...

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

like image 28
WayneC Avatar answered Oct 07 '22 14:10

WayneC