PongGod PongGod - 1 month ago 29
ASP.NET (C#) Question

ASP:Repeater and embedded radiobuttons

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>


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.

Your suggestions are appreciated!

Win Win
Answer

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);
}

When a radio button is clicked, uncheck all radio buttons with myRadioButton class name. Then check only one triggered the click event.

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>

Code Behind

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