编程语言
首页 > 编程语言> > c# – 如何向RadioButtonList项添加自定义属性?

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

作者:互联网

如何将绑定的Html5 data- attribute添加到使用绑定的RadioButtonList生成的项目?

我的代码看起来像这样:

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

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

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

public class Answers
{
    int AnswerId;
    string Answer;
    bool SomeFlag;
}

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

<input type="radio" data-flag="true" ... />

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

解决方法:

您可以在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";
        }
    }
}

并记住为控件设置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>

标签:c,html5,asp-net,radiobuttonlist
来源: https://codeday.me/bug/20190520/1143963.html