如何添加绑定(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/