2

我正在开发在线测验模块。所以我定义了两种类型的问题。

  1. 多项选择单选项(单选按钮)
  2. 多项选择多项选项(复选框)
  3. 其他 Naswer(文本框)

我使用了嵌套中继器。第一个中继器绑定了问题。子中继器绑定可用于问题的选项。

所以我想要的是我想检查条件,

就像我的 QuestionType 是 MS(Multiple Choice Single Option)一样,我会将 4 个选项与单选按钮绑定。

如果它的 MM(Multiple Choice Multiple Option)那么我会将 Options 与 Checkbox 绑定。

那么我怎样才能在 aspx 文件中检查这样的条件和代码呢?

4

1 回答 1

2

这是一种方法:

输出

在此处输入图像描述

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>();
    }
}
于 2012-07-17T16:25:18.003 回答