c# - 如何将自定义属性添加到 RadioButtonList 项目?

标签 c# asp.net html radiobuttonlist

如何添加绑定(bind) Html5 data- attribute到使用绑定(bind) 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();

它绑定(bind)到一个如下所示的类结构:

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 data- 属性添加到从绑定(bind) RadioButtonList 生成的输入对象?

最佳答案

您可以使用 ListItem 属性将自定义属性添加到单选按钮列表中的项目。您可以检查如何为单选按钮列表生成 html,并使 jquery 为您获取所需的数据属性。

在服务器端

ListItem li1 = new ListItem();
ListItem li2 = new ListItem();
li1.Attributes.Add("data-flag", "true");
li2.Attributes.Add("data-flag", "true");
RadioButtonList1.Items.Add(li1);
RadioButtonList1.Items.Add(li2);

为单选按钮列表生成的 html

<table id="RadioButtonList1" border="0">
    <tr>
        <td><span data-flag="true"><input id="RadioButtonList1_0" type="radio" name="RadioButtonList1" value="" /></span></td>
    </tr><tr>
        <td><span data-flag="true"><input id="RadioButtonList1_1" type="radio" name="RadioButtonList1" value="" /></span></td>
    </tr>
</table>

在 jquery 中访问

$(':radio[id*=RadioButtonList1]').click(function(){
      alert($(this).closest('span').data('flag'));
})

关于c# - 如何将自定义属性添加到 RadioButtonList 项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13768930/

相关文章:

php - Cakephp 3.0 更改或删除输入表单上的包装 div

c# - 使用 LINQ 而不是使用 for-each 循环

javascript - webmethod 没有被触发

c# - ImageButton 事件未在更新面板内触发

ASP.NET 应用程序——测试

html - 为什么使用列表作为导航菜单?

javascript - 如何在 HTML 脚本标签中插入任意 JSON

c# - 如何按递增顺序从数组创建整体列表(子列表)

c# - 如何在不刷新页面的情况下运行我的代码?

c# - 没有符号的货币格式