我正在尝试将 xml 文件加载到 ASP.NET MVC 中的下拉列表中。
在layout.cshtml
我有这样的dropdwnlist
@Html.DropDownList("Market", ViewBag.Market as SelectList, new { id = "Market" })
在控制器中,我从 xml 文件中读取并分配如下:
public ActionResult Index()
{
DataSet marketDS = new DataSet();
marketDS.ReadXml(Server.MapPath("~/Content//XmlData/Markets.xml"));
EnumerableRowCollection<DataRow> DV1 = marketDS.Tables["Market"].AsEnumerable();
ViewBag.Market= new SelectList(DV1.ToList<DataRow>(), "ID", "Value");
return View();
}
我收到此错误:
DataBinding:“System.Data.DataRow”不包含名为“ID”的属性。
但我可以在 DV1 中看到它已从 xml 文件中读取并包含 ITEM Array 以及 xml 文件中的所有项目。
我是 ASP.NET MVC 的新手,不知道自己在做什么......过去使用 webforms 将数据绑定到 .cs 文件中的下拉列表非常容易。这里很混乱。有什么帮助吗?
我是这样解决的
//加载 DropDownList 市场数据集的值 marketDS = new DataSet(); marketDS.ReadXml(Server.MapPath("~/Content//XmlData/Markets.xml"));
EnumerableRowCollection<DataRow> DR1 = marketDS.Tables["Market"].AsEnumerable();
List<string> marketList=new List<string>();
foreach (DataRow dr in DR1)
{
marketList.Add(dr.ItemArray[1].ToString());
}
ViewBag.Market = new SelectList(marketList.AsEnumerable().ToList());