Press "Enter" to skip to content

ASP.NET MVC 3 – DropDownList binding with XML

Today I have bumped into a small problem while developing a project using ASP.NET MVC 3: I had to bind the contents of an XML file to a DropDownList control, but for some reasons I was forced to do everything in the View part. Here’s how I solved it, hope it helps…

My code in C#, in the View part:

<label>Country:</label>  
<%= Html.DropDownListFor(  
  r => register.Country,
  new SelectList(
    (from node in  XDocument.Load(System.Web.HttpContext.Current.Server.MapPath("Countries.xml")).Descendants("Country")
      select new ListItem
      (
        node.Element("Name").Value,
        node.Element("Code").Value
      )
    )
  )
)%>

What I did was basically parse the XML when creating the DropDownList and create a ListItem for each “Country” node using the “Name” and “Value” pairs.

The structure of my XML file:

<countries>  
    <country>
        <name>Afghanistan</name>
        {gfm-js-extract-pre-1}
    </country>
    <country>
        <name>Åland Islands</name>
        {gfm-js-extract-pre-2}
    </country>
    <country>
        <name>Albania</name>
        {gfm-js-extract-pre-3}
    </country>
    <country>
        <name>Algeria</name>
        {gfm-js-extract-pre-4}
    </country>
    <country>
        <name>American Samoa</name>
        {gfm-js-extract-pre-5}
    </country>
    <country>
        <name>Andorra</name>
        {gfm-js-extract-pre-6}
    </country>
...
</countries>