这是一种方法:
输出
ASPX
<asp:Repeater runat="server" ID="repeater" DataSourceID="ods"
onitemdatabound="repeater_ItemDataBound">
<ItemTemplate>
<asp:Label Text='<%# Eval("QuestionText") %>' runat="server" />
<br />
<asp:Panel runat="server" ID="panel">
</asp:Panel>
</ItemTemplate>
</asp:Repeater>
<asp:ObjectDataSource ID="ods" runat="server"
SelectMethod="GetQuestions"
TypeName="WebApplication1.Questions.QuestionsContext">
</asp:ObjectDataSource>
背后的代码
protected void repeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
var q = e.Item.DataItem as Question;
if (q == null)
throw new InvalidOperationException();
var panel = e.Item.FindControl("panel");
if (q.MultipleAnswers)
{
var checks = new CheckBoxList { DataSource = q.Answers, DataTextField = "AnswerText", DataValueField = "ID" };
checks.DataBind();
panel.Controls.Add(checks);
}
else
{
var radios = new RadioButtonList { DataSource = q.Answers, DataTextField = "AnswerText", DataValueField = "ID" };
radios.DataBind();
panel.Controls.Add(radios);
}
}
数据组件
这只是为了测试,用你的数据源替换它
public class QuestionsContext
{
public IEnumerable<Question> GetQuestions()
{
var q = Builder<Question>.CreateListOfSize(5).Build().ToList();
q.ForEach(x =>
{
x.ID = Guid.NewGuid();
x.Answers = Builder<Answer>.CreateListOfSize(4)
.All().With(y => y.Question, x)
.Build().ToList();
});
return q;
}
}
模型
public class Answer
{
public Guid ID { get; set; }
public Question Question { get; set; }
public string AnswerText { get; set; }
public bool IsCorrect { get; set; }
}
public class Question
{
public Guid ID { get; set; }
public string QuestionText { get; set; }
public IEnumerable<Answer> Answers { get; set; }
public bool MultipleAnswers { get; set; }
public Question()
{
this.Answers = Enumerable.Empty<Answer>();
}
}