向 asp.NET RadioButton 控件添加自定义属性自定义、控件、属性、asp

2023-09-06 22:05:02 作者:国民萌叔

我想向名为 Key 的 asp.net RadioButton 添加一个自定义属性,我在客户端使用该属性进行 ajax 请求.

I want to add a custom attribute to an asp.net RadioButton called Key which I'm using client-side for an ajax request.

我发现我的 aspx 标记如下:

What I'm finding is that my aspx markup which is the following:

<asp:RadioButton ID="rdoPost" GroupName=PreferredContactMethod" value="Post" onclick="DoStuff(this)" runat="server" />

在页面中呈现为

<span Key="ContactMethod">
   <input id="rdoPost" type="radio" name="PreferredContactMethod"" value="Post" onclick="DoStuff(this);" />
</span>

而我期望(并希望)得到以下结果

whereas I'd expected (and hoped) to get the following

<input id="rdoPost" type="radio" Key="ContactMethod" name="PreferredContactMethod"" value="Post" onclick="DoStuff(this);" />

我用 asp TextBox 控件尝试了同样的事情,它的工作方式与我期望的完全一样,只需将 Key="myKey" 属性添加到 <input type=文本"/> 元素.

I've tried the same thing with an asp TextBox control and it works exactly as I'd expect simply adding the Key="myKey" attribute to the <input type="text"/> element.

标准 RadioButton 控件有没有办法解决这个问题,还是我必须从标准控件继承才能实现我想要的标记?

Is there a way around this with the standard RadioButton control, or will I have to inherit from the standard one to achieve the markup I'm wanting?

另外...(很抱歉同时问两个问题),向 html 标记添加非标准属性是不是一个坏主意?目前我在 JavaScript 中通过以下方式使用这些属性:

Also... (sorry to ask two questions at the same time), is adding non-standard attributes to html markup a bad idea anyway? Currently I'm using these attributes in JavaScript in the following way:

var key = rdoPost.Key;

推荐答案

我从下面的问题/答案中发现,最简单的方法是通过使用 InputAttributes 的代码隐藏属性如下:

I've found from the question/answer below that the easiest way to do this is via the code-behind using the InputAttributes property as follows:

rdoPost.InputAttributes.Add("class", "myCheckBoxClass");

为什么 ASP.NetRadioButton 和 CheckBox 在 Span 内渲染?