我正在编写一个具有 RadioButton 控件列表的 WebApplication,这些控件是根据数据库中的信息动态生成的。我的问题是,我“检查”的 RadioButton 没有显示为被检查。
HTML:
<asp:CustomValidator ID="vgCheckRequiredChoice" Display="Static" runat="server" ValidationGroup="vgTicketTypeChoice"
Text="You must select an office location to continue." ForeColor="Red"></asp:CustomValidator>
<table style="padding: 10px 10px 10px 10px; width: 100%" cellpadding="5px 5px 5px 5px">
<asp:Repeater ID="rptType" runat="server" OnItemDataBound="rptType_ItemDataBound">
<ItemTemplate>
<tr style="border-bottom: solid 1px #000000; padding: 40px 10px 10px 10px;">
<td style="width: 30%;">
<asp:RadioButton runat="server" ID="RadioButtonLocation" Text='<%# Bind("LocationName") %>'
GroupName='<%# Bind("LocationID") %>' ValidationGroup="vgTicketTypeChoice"
CausesValidation="true" />
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
</table>
<div style="float: right; display: inline; padding-right: 20px; padding-top: 20px;">
<asp:Button runat="server" ID="ButtonCancel" Text="Cancel" PostBackUrl="~/Default.aspx" />
<asp:Button runat="server" ID="ButtonDefiningLocation" Text="Next >>"OnClick="ButtonDefiningLocation_Click" />
</div>
这是我用来检查每个唯一 RadioButton 的 JavaScript:
<script type="text/javascript">
function SetUniqueRadioButton(nameregex, current) {
re = new RegExp(nameregex);
for (i = 0; i < document.forms[0].elements.length; i++) {
elm = document.forms[0].elements[i]
if (elm.type === 'radio') {
if (re.test(elm.name)) {
elm.checked = false;
}
}
}
current.checked = true;
}
</script>
最后但并非最不重要的 CodeBehind:
protected void rptType_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem)
return;
RadioButton rdo = (RadioButton)e.Item.FindControl("RadioButtonLocation");
string script =
"SetUniqueRadioButton('rptType.*VisitingOffice',this)";
rdo.Attributes.Add("onclick", script);
}
protected void ButtonDefiningLocation_Click(object sender, EventArgs e)
{
rptType.DataBind();
if (Page.IsValid)
{
foreach (RepeaterItem ri in rptType.Items)
{
switch (ri.ItemType)
{
case ListItemType.Item:
case ListItemType.AlternatingItem:
RadioButton rb = (RadioButton)ri.FindControl("RadioButtonLocation");
if (rb.Checked)
{
var LocationID = rb.GroupName;
DataService ds = new DataService();
DataTable tbl = ds.GetLocation(LocationID);
Response.Write(LocationID);
}
break;
}
}
}
}
如您所见,在代码隐藏中,当我逐步执行程序并进入“rb.checked”时,它将显示 rb 的正确选项(例如:{Text="Houston" Checked= false} 即使选择了休斯顿单选按钮。)
编辑:我已将其追踪到 javascript 函数。javascript 函数未将 current.checked 设置为 true。现在,我不知道为什么在函数中显式调用它时会发生这种情况。任何建议或意见将不胜感激。