SuperWasp

SuperWasp

Productivity tips, reviews, tools, software and gadgets.

 
How-To: Build Language dropdown with ASP.NET MVC and LINQ
Advertisement:

Here's a quick way to build a language dropdown box with ASP.NET MVC Preview 3, without using a database table. In total we need only 3 lines of code.

1. Controller:

Screenshot of MVC Controller Action in VS2008

In our controller, we add the following code to the controller action:

List<System.Globalization.CultureInfo> Locales =
    System.Globalization.CultureInfo.GetCultures(
        System.Globalization.CultureTypes.NeutralCultures).ToList();

ViewData["Locales"] = new SelectList(
    Locales
    .OrderBy(lc => lc.Name.Length)
    .ThenBy(lc => lc.DisplayName),
    "Name",
    "DisplayName");

First we create a list of CultureInfo and store it in a variable Locales. For this example I've used NeutralCultures to limit the entries to the most used languages, otherwise you'll get a very long list.

Next we create a ViewData object and fill it using SelectList, passing along our Locales variable.

Note: I've sorted Locales twice, first with OrderBy and then with ThenBy. As parameter we throw in a Lambda expression to transform our Locales and get the member we want. The reason I sort on Name.Length first is that the Invariant CultureInfo has an empty Name and thus it will be sorted to the top of the list.

After that we simply render our View (in this case passing along a Contact record from the database.

2. View:

The code in our view is even simpler. With the help of Extensions and MVC HtmlHelper objects we have our dropdown box in no time:

Screenshot of MVC View in VS2008

The only line of code to render the fully functional html select dropdown box is this:

<%=Html.DropDownList("Locales") %>

Here is the final result:

Final result: dropdown box

A quick look at the produced code shows us the clean XHTML underneath:

<select name="Locales" id="Locales">
<option value="">Invariant Language (Invariant Country)</option>
<option value="af">Afrikaans</option>
<option value="sq">Albanian</option>
<option value="ar">Arabic</option>
<option value="hy">Armenian</option>
<option value="az">Azeri</option>
<option value="eu">Basque</option>
<option value="be">Belarusian</option>
<option value="bg">Bulgarian</option>
...

Ps: in the screenshots above I've used a test version of TheSansMono OpenType by Luc(as) de Groot. This font will be published soon on the LucasFonts website, together with TheSansCondensed OpenType. Typographer Luc(as) de Groot is also known for the Calibri and Consolas fonts in Windows Vista and Microsoft Office 2007.

Labels: , , , ,

  Posted by oVan on Wednesday, May 28, 2008 | PermaLink | 0 comments
« SuperWasp start page