Saturday, August 25, 2012

A Method for Populating a Dropdown List in ASP.NET MVC

I’m asked quite a bit how to bind a dropdown list in ASP.NET MVC. So there are about 10,000 ways to do it, but here’s one.

First, we’ll create a simple interface to return a list of SelectListItem so we can use the built-in DropDownListFor() later on.

Then we can create a SelectListProviderAttribute to take in the Type of list provider we want. You can see in this example I'm instantiating the object with could do this with Activator or something else.

Now we just implement an ISelectListProvider and add the attribute to our model like this:

Sample property on view model:
public int CommunityId { get; set; }
Now we just call our new HtmlHelper in our view and we're done. So here's the helper:

And now we just call it from the view like this:

@Html.DropDownListFor(x => x.CommunityId)

I'm sure you all realized that I used some additional helpers in code samples above. So for the curious few, I uploaded the full sample project to github. Browse the source now

Shout it

kick it on

blog comments powered by Disqus
Related Posts Plugin for WordPress, Blogger...