Monday, December 28, 2009

US State DropDownList with ASP.NET MVC FluentHtml

I recently ran into this “issue” and thought I’d blog it real quick. So as I mentioned in a previous post, I love FluentHtml and I wanted an easy way to create a state list. So I Googled it and of course popped up with this post. I thought…that works, but I just want the 50 states and I don’t want the full name AND I want to use FluentHtml and not have to create another extension. I used Kyle West’s list as my base to get started.

So I created a UnitedStates class in my Core.UI.Helpers.Common folder (see my MVC structure here) and it looks like this:

    public class UnitedStates
public static readonly IDictionary<string, string> StateDictionary = new Dictionary<string, string>
"AL", "AL"},{"AK", "AK"},{"AZ", "AZ"},{"AR", "AR"},{"CA", "CA"},{"CO", "CO"},
"CT", "CT"},{"DE", "DE"},{"FL", "FL"},{"GA", "GA"},{"HI", "HI"},{"ID", "ID"},
"IL", "IL"},{"IN", "IN"},{"IA", "IA"},{"KS", "KS"},{"KY", "KY"},{"LA", "LA"},
"ME", "ME"},{"MD", "MD"},{"MA", "MA"},{"MI", "MI"},{"MN", "MN"},{"MS", "MS"},
"MO", "MO"},{"MT", "MT"},{"NE", "NE"},{"NV", "NV"},{"NH", "NH"},{"NJ", "NJ"},
"NM", "NM"},{"NY", "NY"},{"NC", "NC"},{"ND", "ND"},{"OH", "OH"},{"OK", "OK"},
"OR", "OR"},{"PA", "PA"},{"RI", "RI"},{"SC", "SC"},{"SD", "SD"},{"TN", "TN"},
"TX", "TX"},{"UT", "UT"},{"VT", "VT"},{"VA ", "VA"},{"WA", "WA"},{"WV", "WV"},
"WI", "WI"},{"WY", "WY"}};

I wanted to keep it an IDictionary in case I ended up wanting to use the full state name, but as you can see, pretty basic stuff. Now for the fluent goodness.

=this.Select(f => f.MailingAddressState).Options(UnitedStates.StateDictionary).Selected("TX")%>

If you’re familiar with FluentHtml, then you know what the lambda is in the Select(), otherwise, go checkout FluentHtml or this previous post. After the Select() call, I call the Options() and pass in my StateDictionary and then call Selected(“TX”) to set the default selection. Good stuff!

Please let me know if you have any questions or if you see anything that I can improve. Thanks for reading!

kick it on

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