kk1076
kk1076

Reputation: 1748

Reading XML contents through LINQ to Dropdownlist

I am binding the XML contents to a Dropdownlist in MVC4. From the link, I tried reading the contents of the XML file. The Where clause in the code returns Object is not reffered to the instance of the object. Without the where condition the xml contents are read from the file. I want to display only the values based on the capitals ID=1.
XML

<?xml version="1.0" encoding="utf-8"?>
<State>
<Capital ID="1" CountryName="India">
    <city name="Andaman and Nicobar Islands" value="AN"></city>
    <city name="Andhra Pradesh" value="AP"></city>
</Capital>  
<Capital ID="2" CountryName="USA">
    <city name="Alabama" value="AL"></city>
    <city name="Alaska" value="AK"></city>
</Capital>  
</State>

Controller

 public ActionResult Details()
{
 string UserID = 12345;
 string partnerid = XCWERT;
 var file = Path.Combine(Server.MapPath("~/App_Data"), "States.xml");            
 var model = new CheckoutModel
 {    
  States =
  from unit in XDocument.Load(file).Document.Elements("State").Elements("Capital").Elements("city") -- This loads all the values
  //   from unit in XDocument.Load(file).Document.Descendants("Capital").Where(unit => (string)unit.Attribute("ID").Value == "1") -- where condition is not accepting and throwing error
   select new SelectListItem
  {
    Text = unit.Attribute("name").Value,
    Value = unit.Attribute("value").Value,                      
  }                     
};
 SelectList selectList = new SelectList(model.States, "Value", "Text");
 ViewData["StateOptions"] = selectList;          
 return View(GetShippingAddress(UserID, partnerid));
 }

View

 @Html.DropDownList("State", ViewData["StateOptions"] as IEnumerable<SelectListItem>, "(Select one)", new { @class = "TextBoxBorder" })

What is the mistake in my code. ? Any suggesstions will be greatly helpful

Upvotes: 0

Views: 686

Answers (1)

I4V
I4V

Reputation: 35353

It should be something like this

var result = XDocument.Load(fileName)
                .Descendants("Capital")
                .First(c => (string)c.Attribute("ID") == "1")
                .Descendants("city")
                .Select(c => new
                {
                    Text = (string)c.Attribute("name"),
                    Value = (string)c.Attribute("value"),
                })
                .ToList();

Upvotes: 2

Related Questions