2
所以我有以下的ASP.NET代碼。本質上,我試圖展示一個「考試」對象。考試由幾個字符串組成,然後是問題的嵌套集合。問題有一個嵌套的答案集合。當我運行它時,我收到一個錯誤消息: 無法投射'System.Char'類型的對象以鍵入'PracticeNet.DataEntities.Question'。ASP.NET嵌套的ListView數據綁定
System.InvalidCastException:無法將類型爲 'System.Char'的對象強制類型爲'PracticeNet.DataEntities.Question'。
線15:<%#:Item.QuestionTitle%>
我不知道爲什麼我收到這個錯誤。我在Question類的任何地方都沒有任何字符類型。我唯一的猜測是,我有點從根本上誤解了嵌套的ListView對象模型。任何人都可以對此有所瞭解嗎?完整代碼如下。
<asp:Content ID="Content2" ContentPlaceHolderID="FeaturedContent" runat="server">
<asp:FormView ID="examDetails" runat="server" ItemType="PracticeNet.DataEntities.Exam" SelectMethod="GetExam" RenderOuterTable="false">
<ItemTemplate>
<div>
<h1><%#:Item.ExamTitle %></h1>
<h2><%#:Item.Description %></h2>
</div>
<br />
<asp:ListView ID="examQuestions" runat="server" ItemType="PracticeNet.DataEntities.Question" DataSource="<%#:Item.Questions %>">
<ItemTemplate>
<div>
<h1><%#:Item.QuestionTitle %></h1>
<h2><%#:Item.QuestionText %></h2>
</div>
<br />
<asp:ListView ID="questionAnswers" runat="server" ItemType="PracticeNet.DataEntities.Answer" DataSource="<%#:Item.AnswerOptions %>">
<ItemTemplate>
<div>
<h1><%#:Item.AnswerText %></h1>
</div>
</ItemTemplate>
</asp:ListView>
</ItemTemplate>
</asp:ListView>
</ItemTemplate>
</asp:FormView>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">
</asp:Content>
考試類別:
public class Exam
{
[Required]
public Guid ExamId
{
get;
set;
}
[Required, StringLength(512),Display(Name="Title")]
public string ExamTitle
{
get;
set;
}
[Required, StringLength(1024),Display(Name="Details")]
public string Description
{
get;
set;
}
[Required]
public virtual ICollection<Question> Questions
{
get;
set;
}
}
問題類別:
public class Question
{
public Question()
{
QuestionId = Guid.NewGuid();
AnswerOptions = new List<Answer>();
}
[Key]
public Guid QuestionId
{
get;
set;
}
[Required, StringLength(120), Display(Name="Title")]
public string QuestionTitle
{
get;
set;
}
[Required,StringLength(255), Display(Name="Text")]
public string QuestionText
{
get;
set;
}
[Required]
public virtual ICollection<Answer> AnswerOptions
{
get;
set;
}
}
最後,答案類:
public class Answer
{
public Answer()
{
AnswerId = Guid.NewGuid();
}
[Key]
public Guid AnswerId
{
get;
set;
}
[Required, StringLength(250), Display(Name="Answer")]
public string AnswerText
{
get;
set;
}
}
我相信你正在使用「DataSource」字段的錯誤ASP標記。它應該是'<%#Item.AnswerOptions%>'你有':'在那裏是不必要的。 – debracey
你試過用'<%#'替換'<%#:'看起來有嫌疑嗎? – James
是的,用<%#替換<%#:似乎已經做到了。謝謝! – GWLlosa