问题描述
我正在使用中继器控件在 ASP.NET Web 表单上显示一系列照片.这是我当前的代码:
I'm using a Repeater control to display a series of photos on an ASP.NET web form. Here is my current code:
<asp:Repeater ID="repPhotos" runat="server">
<ItemTemplate>
<asp:hyperlink id="link" NavigateUrl='<%# Container.DataItem %>' runat="server">
<asp:Image ID="Image" runat="server" ImageUrl='<%# Container.DataItem %>' Height="10%" Width="10%" />
</asp:hyperlink>
</ItemTemplate>
</asp:Repeater>
现在我想在每张照片下方显示一个单选按钮,但一系列单选按钮必须是互斥的.我尝试使用 ASP:RadioButton 控件,但在阻止同时选择多个单选按钮时遇到了困难,我不确定 ASP:RadioButtonList 如何与中继器一起使用.
Now I would like to include a radiobutton displayed beneath each photo, but the series of radiobuttons must be mutually exclusive. I tried using the ASP:RadioButton control, but was having difficulty preventing multiple radiobuttons from being simultaneously selected and I'm not sure how the ASP:RadioButtonList could work with the Repeater.
感谢您的建议!
推荐答案
不幸的是,RadioButton 的 GroupName 在 Repeater 或 GridView 中不起作用 如果它们放在单独的行中.但是,您可以使用几行 jQuery 轻松实现它.
Unfortunately, RadioButton's GroupName doesn't work inside Repeater or GridView if they are placed inside individual row. However, you can easily achieve it using a couple of line of jQuery.
function radioButtonClick(sender) {
$('.myRadioButton input').attr("checked", false);
$(sender).prop("checked", true);
}
单击单选按钮时,取消选中所有具有 myRadioButton 类名称的单选按钮.然后检查只有一个触发了点击事件.
When a radio button is clicked, uncheck all radio buttons with myRadioButton class name. Then check only one triggered the click event.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="DemoWebForm.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:Repeater ID="repPhotos" runat="server">
<ItemTemplate>
<asp:RadioButton runat="server" ID="PhotoRadioButton"
CssClass="myRadioButton" onclick="radioButtonClick(this)" />
<%# Container.DataItem %>
</ItemTemplate>
</asp:Repeater>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script>
function radioButtonClick(sender) {
$('.myRadioButton input').attr("checked", false);
$(sender).prop("checked", true);
}
</script>
</form>
</body>
</html>
背后的代码
using System;
using System.Collections.Generic;
namespace DemoWebForm
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
repPhotos.DataSource = new List<string> {"One", "Two", "Three"};
repPhotos.DataBind();
}
}
}
这篇关于ASP:中继器和嵌入式单选按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!