From the Geek's Head

Drop Down List XML hack in MVC

Today I ran into a situation where I had to populate a drop down list inside a razor view with some data. I did not want to get the data from the database, I wanted a simpler approach so I decided to use an XML file to populate my dropdown list. Here’s how I did it:

First I created an XML file:

<?xml version="1.0" encoding="utf-8" ?>
<Countries>
  <Country name="Pakistan" value="PK"></Country>
  <Country name="America" value="USA"></Country>
  <Country name="England" value="UK"></Country>
</Countries>

Then after doing a barrell roll, I proceeded to write some code inside my controller to take the data from this XML file and put it inside the magical ViewBag:

string path = "~/Countries.xml";
            XDocument xdoc = XDocument.Load(Server.MapPath(path));
            IEnumerable<XElement> result = from c in xdoc.Elements("Countries").Elements("Country")
                                           select c;

            var listItems = new List<SelectListItem>();

            foreach (var xElement in result)
            {
                listItems.Add(new SelectListItem
                {
                    Text = xElement.Attribute("name").Value,
                    Value = xElement.Attribute("value").Value,
                });
            }
            SelectList selectList = new SelectList(listItems, "Value", "Text");
            ViewBag.countries = selectList;

Pretty simple stuff I am just loading the XML file inside a XDocument, using Linq to traverse and create an IEnumerable to hold all the countries in. Aftewards I create a SelecList(So that I can use the data inside a DropDownList) and pass it on to the super awesome dynamic ViewBag. The last piece of the puzzle is offcourse the razor view where I show this data from the XML file inside a dd, here is how that is implemented:

@Html.DropDownListFor(model => model.Country, (IEnumerable)ViewBag.countries)

Thats it, a super simple quick hack to populate your dropdowns. Rock On!

blog comments powered by Disqus