【问题标题】:How to find checked RadioButton inside Repeater Item?如何在中继器项中找到选中的 RadioButton?
【发布时间】:2010-09-22 08:18:20
【问题描述】:

我在 ASPX 页面上有一个 Repeater 控件,定义如下:

<asp:Repeater ID="answerVariantRepeater" runat="server"
    onitemdatabound="answerVariantRepeater_ItemDataBound">
    <ItemTemplate>
        <asp:RadioButton ID="answerVariantRadioButton" runat="server"
            GroupName="answerVariants" 
            Text='<%# DataBinder.Eval(Container.DataItem, "Text")%>'"/>
    </ItemTemplate>
</asp:Repeater>

为了允许及时选择一个单选按钮,我使用了一个技巧表单this article

但是现在提交表单时,我想确定选中的是哪个单选按钮。

我可以这样做:

RadioButton checkedButton = null;

foreach (RepeaterItem item in answerVariantRepeater.Items)
{
    RadioButton control=(RadioButton)item.FindControl("answerVariantRadioButton");
    if (control.Checked)
    {
        checkedButton = control;
        break;
    }
}

但希望它可以以某种更简单的方式完成(可能通过 LINQ to 对象)。

【问题讨论】:

    标签: asp.net javascript repeater radio-button


    【解决方案1】:

    您总是可以使用Request.Form 来获取提交的单选按钮:

    var value = Request.Form["answerVariants"];
    

    我认为提交的值默认为所选 &lt;asp:RadioButton /&gt; 的 id,但您始终可以添加 value 属性 - 即使它不是正式的 &lt;asp:RadioButton /&gt; 属性 - 然后这将是提交的值:

    <asp:RadioButton ID="answerVariantRadioButton" runat="server"
        GroupName="answerVariants" 
        Text='<%# DataBinder.Eval(Container.DataItem, "Text")%>'"
        value='<%# DataBinder.Eval(Container.DataItem, "SomethingToUseAsTheValue")%>' />
    

    【讨论】:

      【解决方案2】:

      由于您已经使用 javascript 来处理客户端上的单选按钮单击事件,您可以同时使用所选值更新隐藏字段。

      然后,您的服务器代码将只访问隐藏字段中的选定值。

      【讨论】:

      • 您问题中的原始解决方案或者这将很好地工作。
      【解决方案3】:

      我很确定在这里您可以使用 LINQ to Objects 的唯一方法就是从 foreach 循环中获取条件并将它们移动到 where 子句。

      RadioButton checked = 
          (from item in answerVariantRepeater.Items
          let radioButton = (RadioButton)item.FindControl("answerVariantRadioButton")
          where radioButton.Checked
          select radioButton).FirstOrDefault();
      

      【讨论】:

      • 也许可以避免同时使用 Items 和 FindControl 来支持某些 Controls 集合。
      • 我从未见过从模板化父控件获取控件实例的不同方法。最简单的方法是使用 RadioButtonList,但我假设您的示例为清晰起见进行了简化,并且模板中还有其他控件阻止您使用它。
      猜你喜欢
      • 2013-10-10
      • 2011-08-09
      • 2016-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-20
      • 2013-03-18
      • 1970-01-01
      相关资源
      最近更新 更多