【问题标题】:ASP:Repeater and embedded radiobuttonsASP:Repeater 和嵌入式单选按钮
【发布时间】:2017-02-22 17:28:38
【问题描述】:

我正在使用Repeater 控件在ASP.NET Web 表单上显示一系列照片。这是我当前的代码:

<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 如何与中继器一起使用。

感谢您的建议!

【问题讨论】:

标签: asp.net webforms radio-button repeater


【解决方案1】:

很遗憾,RadioButton 的GroupName 在Repeater 或GridView 中不起作用如果它们被放置在单独的行中。但是,您可以使用几行 jQuery 轻松实现它。

function radioButtonClick(sender) {
    $('.myRadioButton input').attr("checked", false);
    $(sender).prop("checked", true);
}

单击单选按钮时,取消选中所有具有 myRadioButton 类名称的单选按钮。然后检查只有一个触发了点击事件。

ASPX

<%@ 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();
        }
    }
}

【讨论】:

  • 这成功了!但是单选按钮出现在每个图像的左侧。我希望让它们出现在图像下方,但还没有设法弄清楚这一点。有什么建议吗?
  • 您想使用 CSS 或 html 标签来设置样式。最简单的方法是将它放在&lt;p&gt; 标签内。例如,&lt;ItemTemplate&gt;&lt;p&gt;&lt;asp:RadioButton ..&gt;&lt;/p&gt;&lt;/ItemTemplate&gt;
  • 这样做的问题是,在将单选按钮包裹在

    标签中之后,现在照片会垂直向下显示,而不是水平显示在页面上。

  • 您能创建一个新问题,包括标记和屏幕截图吗?
猜你喜欢
  • 2017-02-23
  • 2015-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-07
  • 2015-12-09
相关资源
最近更新 更多