在ListView的asp.net选择单选按钮检索值 [英] Retrieve value for selected radiobutton in ListView asp.net

查看:96
本文介绍了在ListView的asp.net选择单选按钮检索值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想送它应作为EventArgs的每个单选按钮,当用户点击结账关联的GUID。我可以只是一个单选按钮列表来实现这一功能,但我不能在这里为场的其余部分从数据库中抽取使用。

I would like to send a Guid which should be associated with each radio button as eventargs when the user clicks checkout. I was able to achieve this functionality with just a RadioButtonList but I cannot use that here as the rest of the fields are pulled from the database.

有处理这类话题的很多问题,但我无法找到一个解决正是我想要的目的。

There are numerous questions dealing with this type of topic but I could not find one that addresses exactly what I am trying to achieve.

我有文章

<asp:Content ID="SubscriptionContent" ContentPlaceHolderID="MainContent" ViewStateMode="Enabled" runat="server">
    <asp:Panel ID="SubscriptionPanel" CssClass="shopping-cart" ViewStateMode="Enabled" runat="server">
        <asp:ListView ID="NewSubscription" runat="server">
            <LayoutTemplate>
                <table class="table">
                    <thead>
                        <th>Select a Subscription</th>
                        <th>Subscription Level
                        </th>
                        <th>Description
                        </th>
                        <th>Price
                        </th>
                    </thead>
                    <tbody>
                        <tr id="itemPlaceholder" runat="server" />
                    </tbody>
                </table>
            </LayoutTemplate>
            <ItemTemplate>
                <tr>
                    <td class="description"><asp:RadioButton ID="SubscriptionLevel" GroupName="SubscriptionRadio" Text='<%# Eval("SubscriptionLevel") %>' runat="server" /></td>
                    <td class="description"><asp:Label ID="Details" Text='<%# Eval("Details") %>' runat="server"></asp:Label></td>
                    <td class="price"><asp:Label runat="server" Text='<%# Eval("Price", "{0:C2}") %>'></asp:Label></td>
                    <asp:TextBox ID="Id" runat="server" Visible="false" Text='<%# Eval("Id") %>' />
                </tr>
            </ItemTemplate>
        </asp:ListView>

        <asp:Button ID="Subscribe" CssClass="btn btn-primary" runat="server" Text="<%$ Snippet: Ecommerce/ShoppingCart/CheckoutButtonLabel, Checkout %>" OnClick="BuySubscription" />
        <script type="text/javascript">
            $(document).ready(function () {
                $("input:radio").attr('name', 'SubscriptionRadio');//Override the naming that asp does                   
            });
        </script>
    </asp:Panel>
</asp:Content>

我在想,如果我可以为每个单选按钮对应的GUID值更新的隐藏字段,并提交当用户触发 BuySubscription 。我不知道如何做到这一点,虽然。最后,我只是希望用户能够选择的订阅选项之一,并传递GUID回功能。

I am thinking that if I could update a hidden field with the corresponding guid value for each radio button and submit that when the user triggers BuySubscription. I am not sure how to do this though. Ultimately I just want the user to be able to select one of the subscription options and pass that guid back to the function.

感谢您事先的任何输入。

Thank you in advance for any input.

推荐答案

你要碰到的第一个问题是,ASP.NET给每个&LT;输入类型=电台/&GT ; 一个不同的名称,因为它是在不同的 NamingContainer

The first problem you're going to run into is that ASP.NET gives each <input type="radio" /> a different name, because it's in a different NamingContainer.

您已经添加了一些脚本来尝试通过修改客户机上的名称属性来解决这一点。不幸的是,这是不行的。时后的形式回服务器,ASP.NET仍将使用所生成的名称,这将不存在寻找一个值

You've added some script to try to work around that by changing the name attribute on the client. Unfortunately, this won't work. When you post the form back to the server, ASP.NET will still be looking for a value using the generated name, which won't exist.

快速和肮脏的解决办法是更新脚本,从隐藏的文本框的值复制到单选按钮的value属性。那么你将不得不使用的Request.Form [SubscriptionRadio] 来检索所选选项的值:

The quick and dirty solution would be to update your script to copy the value from the hidden TextBox to the value attribute of the radiobutton. You would then have to use Request.Form["SubscriptionRadio"] to retrieve the value of the selected option:

<ItemTemplate>
    <tr>
        <td class="description">
            <asp:RadioButton ID="SubscriptionLevel" runat="server"
                GroupName="SubscriptionRadio" 
                Text='<%# Eval("SubscriptionLevel") %>' 
            />
            <%-- NB: Can't set Visible="False", otherwise it's not rendered: --%>
            <asp:TextBox ID="Id" runat="server" 
                Style="display:none;"
                Text='<%# Eval("Id") %>' 
            />
        </td>
        ...
    </tr>
</ItemTemplate>
...
<script>
$(document).ready(function() {
    $("input:radio").each(function(){
        var me = $(this);
        var id = me.closest("tr").find("input[name$=Id]").val();
        me.attr("value", id);
        me.attr('name', 'SubscriptionRadio');
    });
});
</script>

另外,你可以使用自定义单选控件的数据绑定控件在其中起作用。我贴一个简单的例子,早在2012: http://stackoverflow.com/a/13271444/124386

Alternatively, you could use a custom RadioButton control which works within a data-bound control. I posted a simple example back in 2012: http://stackoverflow.com/a/13271444/124386

using System;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Reflection;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SiteControls
{
    [ToolboxData("<{0}:ListRadioButton runat=\"server\" />")]
    public class ListRadioButton : RadioButton
    {
       private static readonly FieldInfo UniqueGroupNameField = FindUniqueGroupNameField();
       private string _uniqueGroupName;

       private static FieldInfo FindUniqueGroupNameField()
       {
          return typeof(RadioButton).GetField("_uniqueGroupName", 
             BindingFlags.NonPublic | BindingFlags.Instance);
       }

       public string Value
       {
           get { return Attributes["value"]; }
           set { Attributes["value"] = value; }
       }

       protected virtual string CreateUniqueGroupName()
       {
          string result = GroupName;
          if (string.IsNullOrEmpty(result))
          {
             result = ID;
          }
          if (string.IsNullOrEmpty(result))
          {
             result = UniqueID;
          }
          else
          {
             Control container = NamingContainer;
             if (container != null)
             {
                if (container is IDataItemContainer)
                {
                   container = container.NamingContainer ?? container;
                }

                result = container.UniqueID + base.IdSeparator + result;
             }
             else
             {
                string uniqueID = UniqueID;
                if (!string.IsNullOrEmpty(uniqueID))
                {
                   int index = uniqueID.LastIndexOf(base.IdSeparator);
                   if (index != -1)
                   {
                      result = uniqueID.Substring(0, 1 + index) + result;
                   }
                }
             }
          }

          return result;
       }

       private void EnsureUniqueGroupName()
       {
          if (_uniqueGroupName == null)
          {
             string value = CreateUniqueGroupName();
             if (UniqueGroupNameField != null) UniqueGroupNameField.SetValue(this, value);
             _uniqueGroupName = value;

             value = base.Attributes["value"];
             if (string.IsNullOrEmpty(value))
             {
                base.Attributes["value"] = UniqueID;
             }
          }
       }

       protected override bool LoadPostData(string postDataKey, NameValueCollection postCollection)
       {
          EnsureUniqueGroupName();
          return base.LoadPostData(postDataKey, postCollection);
       }

       protected override void Render(HtmlTextWriter writer)
       {
          EnsureUniqueGroupName();
          base.Render(writer);
       }
    }
}

您既可以在注册页面标记的控件:

You can either register the control in the page markup:

<%@ Register tagPrefix="site" namespace="SiteControls" %>

的web.config 文件:

<?xml version="1.0"?>
<configuration>
    <system.web>
        <pages>
            <controls>
                <add 
                    tagPrefix="site" 
                    namespace="SiteControls"
                />
            </controls>
        </pages>
    </system.web>
</configuration>

通过在地方,你可以失去的脚本和隐藏文本框

With that in place, you can lose the script and the hidden TextBox:

<ItemTemplate>
    <tr>
        <td class="description"><site:ListRadioButton ID="SubscriptionLevel" runat="server"
            GroupName="SubscriptionRadio" 
            Text='<%# Eval("SubscriptionLevel") %>'
            Value='<%# Eval("Id") %>'
        /></td>
        ...

要找到所选的项目,那么你会通过的ListView 产品,找到需要循环单选控制,并期待在经过属性:

To find the selected item, you would then need to loop through the ListView's Items, find the RadioButton control, and look at the Checked property:

ListRadioButton selectedItem = NewSubscription.Items
    .Select(item => (ListRadioButton)item.FindControl("SubscriptionLevel"))
    .FirstOrDefault(radio => radio != null && radio.Checked);

string selectedValue = (selectedItem == null) ? null : selectedItem.Value;

这篇关于在ListView的asp.net选择单选按钮检索值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆