MVC新手请教:从XML文件获取数据绑定至DROPDOWNLIST。
如题:列出代码如下:
A.XML文件:
<YearTable>
<yearNumber>2005</yearNumber>
<yearNumber>2006</yearNumber>
</YearTable>
public SelectList LoadYearDataFromXml
{
get
{
try
{
DataSet ds = new DataSet();
ds.ReadXml(System.Web.HttpContext.Current.Server.MapPath("~/App_Data/xmlData_Years.xml"));
DataTable dt = ds.Tables[0];
EnumerableRowCollection<DataRow> rows = dt.AsEnumerable();
List<DataRow> _item = rows.ToList<DataRow>();
return new SelectList(_item);
}
catch
{
return null;
}
}
}
// GET: /System_MonthMaxMoneySetting/Create
public ActionResult Create()
{
System_MonthMaxMoneySetting mmms = new System_MonthMaxMoneySetting();
ViewBag.Items = mmms.LoadYearDataFromXml;
return View();
}
<div class="editor-field">
@Html.DropDownListFor(model => model.IYear,ViewBag.Items as SelectList)
@Html.ValidationMessageFor(model => model.IYear)
</div>
<select data-val="true" data-val-number="字段 Year 必须是一个数字。" data-val-required="Year 字段是必需的。" id="IYear" name="IYear"><option>System.Data.DataRow</option>
<option>System.Data.DataRow</option>
<option>System.Data.DataRow</option>
</select>
public List<SelectListItem> LoadYearDataFromXml
{
get
{
try
{
DataSet ds = new DataSet();
ds.ReadXml(System.Web.HttpContext.Current.Server.MapPath("~/Content/A.xml"));
DataTable dt = ds.Tables[0];
EnumerableRowCollection<DataRow> rows = dt.AsEnumerable();
List<DataRow> item = rows.ToList();
return item.Select(dataRow => new SelectListItem
{
Text = dataRow[0].ToString(), Value = dataRow.ItemArray[0].ToString(),
}).ToList();
}
catch
{
return null;
}
}
}