所以我有以下ASP.NET代码。基本上,我正在尝试显示“考试”对象。考试由几个字符串组成,然后是一组嵌套的问题。问题有一组嵌套的答案。当我运行它时,我收到一条错误消息: 无法将“System.Char”类型的对象强制转换为“PracticeNet.DataEntities.Question”。
System.InvalidCastException:无法转换类型的对象 'System.Char'输入'PracticeNet.DataEntities.Question'。
第15行:<%#:Item.QuestionTitle%>
我不知道为什么我收到这个错误。我在Question类附近没有任何char类型。我唯一的猜测是,我在某种程度上从根本上误解了嵌套的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;
}
}
答案 0 :(得分:2)
(因为每个问题都需要以答案的形式回答)
正如@James和@debracey的评论已经表明的那样,你的服务器标签是错误的:
替换
<%#: Item.AnswerOptions %>
使用
<%# Item.AnswerOptions %>