通过 SelectListItem 我得到“System.NullReferenceException:对象引用未设置为对象的实例。” 错误。我错了什么?
这是我的xml:
<?xml version="1.0" encoding="utf-8"?>
<Artiesten>
<Item ID_Artiest="509998" Artiest="-" Product="-" Land="" Plaats="" Website="" Genre="Onbekend" />
<Item ID_Artiest="970119" Artiest="(hed)p.e." Product="-" Land="" Plaats="" Website="" Genre="Onbekend" />
<Item ID_Artiest="970080" Artiest="(urusei) yatsura" Product="-" Land="" Plaats="" Website="" Genre="Noise" />
<Item ID_Artiest="1010302" Artiest="...and you will know us by the trail of dead" Product="-" Land="Verenigde Staten" Plaats="Austin (TX)" Website="" Genre="Noise" />
...
</Artiesten>
这是我的模特
public class ArtiestInfoModel
{
[DisplayName("Selecteer artiest: ")]
public int ID_Artiest { get; set; }
public string SelectedArtiest { get; set; }
public IEnumerable<SelectListItem> ArtiestenLijst { get; set; }
}
控制器:
public ActionResult Index(int? AID_Artiest=810000)
{
var document = XDocument.Load(Server.MapPath("~/App_Data/Artiesten.xml"));
var query = new ArtiestInfoModel
{
ArtiestenLijst =
(from artiest in document.Descendants("Artiesten").Elements("Item")
select new SelectListItem
{
Value = artiest.Attribute("ID_artiest").Value,
Text = artiest.Attribute("Artiest").Value,
Selected = false // artiest.Attribute("ID_artiest").Value == AID_Artiest.ToString()
}).ToList()
};
ViewBag.ID_Artiest = AID_Artiest.Value;
ViewBag.ArtiestenLijst = query.ArtiestenLijst;
return View();
}
控制器由下一个 DropDownList 调用:
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<% using (Html.BeginForm("Index", "Hitdossier", FormMethod.Post, new { id = "frmArtiest" })) %>
<% { %>
<table><tr><th width="1000" align="left">Selecteer artiest:</th></tr>
<tr>
<td><%= Html.DropDownList("ID_Artiest",
new SelectList(ViewBag.ArtiestenLijst, "Value", "Text"),
"-- Selecteer artiest --",
new
{
@onchange = "document.getElementById('frmArtiest').submit();"
})%>
</td>
</tr>
</table>
<br />
<br />
<div id="divPartialView">
<%= Html.Action("Detail_Hitdossier", new { AID_Artiest = ViewBag.ID_Artiest })%> <br />
</div>
<%} %>
</asp:Content>
谢谢