如何向RadioButtonList项添加自定义属性?

Rac*_*hel 5 c# asp.net html5 radiobuttonlist

如何将绑定的Html5数据属性添加到使用绑定生成的项目RadioButtonList

我的代码看起来像这样:

<asp:Repeater Id="QuestionList" ...>
    <ItemTemplate>
        <asp:RadioButtonList DataSource='<%# Eval("Answers") %>'
                         SelectedValue='<%# Eval("SelectedAnswerId") %>'
                         DataTextField="Answer" 
                         DataValueField="AnswerId"
                         Tag='<%# Eval("QuestionId") %>' />
    </ItemTemplate>
</asp:Repeater>
Run Code Online (Sandbox Code Playgroud)
var List<Question> questions = GetQuestions();
QuestionList.DataSource = questions;
QuestionList.DataBind();
Run Code Online (Sandbox Code Playgroud)

它绑定到类结构,如下所示:

public class Question
{
    int QuestionId;
    string Question;
    List<Answer> Answers;
}

public class Answers
{
    int AnswerId;
    string Answer;
    bool SomeFlag;
}
Run Code Online (Sandbox Code Playgroud)

我需要添加SomeFlag到用于jQuery的UI,因此最终结果是生成的每个项应如下所示:

<input type="radio" data-flag="true" ... />
Run Code Online (Sandbox Code Playgroud)

有没有办法将html数据属性添加到从绑定生成的输入对象RadioButtonList

Fel*_*ani 1

您可以在 Repeater 的 ItemDataBound 事件中设置一个属性,尝试如下:

protected void repeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    // if it is an item (not header or footer)
    if (e.Item.ItemType == ListItemType.Item)
    {
        // get your radioButtonList
        RadioButtonList optionsList = (RadioButtonList)e.Item.FindControl("rblOptionsList");

        // loop in options of the RadioButtonList
        foreach (ListItem option in optionsList.Items)
        {
            // add a custom attribute
            option.Attributes["data-flag"] = "true";
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

并记住为您的控件设置 ID 和事件

<asp:Repeater Id="QuestionList" ItemDataBound="QuestionList_ItemDataBound" ...>
    <ItemTemplate>
        <asp:RadioButtonList ID="rblOptionsList" DataSource='<%# Eval("Answers") %>'
                         SelectedValue='<%# Eval("SelectedAnswerId") %>'
                         DataTextField="Answer" 
                         DataValueField="AnswerId"
                         Tag='<%# Eval("QuestionId") %>' />
    </ItemTemplate>
</asp:Repeater>
Run Code Online (Sandbox Code Playgroud)