如何在 ASP.NET 中找到所选 RadioButton 的值?
我有两个 asp:RadioButton
控件,它们具有相同的 GroupName
,这本质上使它们互斥。
我的标记:
<asp:RadioButton ID="OneJobPerMonthRadio" runat="server"
CssClass="regtype"
GroupName="RegistrationType"
ToolTip="125"/>
<asp:RadioButton ID="TwoJobsPerMonthRadio" runat="server"
CssClass="regtype"
GroupName="RegistrationType"
ToolTip="200"/>
我的目的是找到选中的 RadioButton 的工具提示/文本。我有这样的代码隐藏:
int registrationTypeAmount = 0;
if (OneJobPerMonthRadio.Checked)
{
registrationTypeAmount = Convert.ToInt32(OneJobPerMonthRadio.ToolTip);
}
if (TwoJobsPerMonthRadio.Checked)
{
registrationTypeAmount = Convert.ToInt32(TwoJobsPerMonthRadio.ToolTip);
}
我发现该代码丑陋且多余。 (如果我有 20 个复选框怎么办?)
是否有一种方法可以从一组具有相同 GroupName
的 RadioButton 中获取选中的 RadioButton
?如果没有,那么编写一个的指导是什么?
PS:在这种情况下我无法使用 RadioButtonList
。
I have two asp:RadioButton
controls which are having the same GroupName
which essentially makes them mutually exclusive.
My markup:
<asp:RadioButton ID="OneJobPerMonthRadio" runat="server"
CssClass="regtype"
GroupName="RegistrationType"
ToolTip="125"/>
<asp:RadioButton ID="TwoJobsPerMonthRadio" runat="server"
CssClass="regtype"
GroupName="RegistrationType"
ToolTip="200"/>
My intention was to find the tooltip / text of the RadioButton that is checked. I have this code-behind:
int registrationTypeAmount = 0;
if (OneJobPerMonthRadio.Checked)
{
registrationTypeAmount = Convert.ToInt32(OneJobPerMonthRadio.ToolTip);
}
if (TwoJobsPerMonthRadio.Checked)
{
registrationTypeAmount = Convert.ToInt32(TwoJobsPerMonthRadio.ToolTip);
}
I find that code ugly and redundant. (What if I have 20 checkboxes?)
Is there a method that would get the checked RadioButton
from a set of RadioButtons with the same GroupName
? And if not, what are the pointers on writing one?
P.S: I cannot use a RadioButtonList
in this scenario.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您想要执行此操作:
其中 radioButtonsContainer 是单选按钮的容器。
更新
如果您想确保获得具有相同组的RadioButtons,您有2个选择:
将它们放在单独的容器中
将组过滤器添加到 lamdba 表达式中,如下所示:
<代码>rb => rb.已检查 && rb.GroupName == "YourGroup"
更新 2
修改了代码,确保在没有选择 RadioButton 的情况下不会失败,从而使其更加防失败。
You want to do this:
where radioButtonsContainer is the container of the radiobuttons.
Update
If you want to ensure you get RadioButtons with the same group, you have 2 options:
Get them in separate containers
Add the group filter to the lamdba expression, so it looks like this:
rb => rb.Checked && rb.GroupName == "YourGroup"
Update 2
Modified the code to make it a little more fail proof by ensuring it won't fail if there's no RadioButton selected.
您可以尝试写下与下面类似的方法:
然后,您可以像这样调用该方法:
它将返回选定的方法(如果有),并且无论您有多少个单选按钮,它都将起作用。如果您愿意,您可以重写该方法,以便它返回 SelectedValue。
You may try writing down a similar method to the one below:
Then, you can call the method like this:
It will return the selected one (if there is) and it will work for no matter how many radio buttons you have. You can rewrite the method, so that it returns the SelectedValue, if you wish.