gpt4 book ai didi

c# - 带有动态单选按钮的附加 html 标签

转载 作者:太空宇宙 更新时间:2023-11-04 13:34:38 26 4
gpt4 key购买 nike

我正在通过以下方式动态创建一些单选按钮:

地区.ascx

<ul class="form_items" ID="radioList" runat="server" clientidmode="Static">    
</ul>

在 Regions.ascx.cs 中

 foreach (var region in Config.ConfigString("str_Regions").Split(','))
{
HtmlGenericControl li = new HtmlGenericControl("li");
RadioButton regionRadio = new RadioButton();
regionRadio.Text = region;
regionRadio.ID = "Radio"+(i++).ToString();
regionRadio.Attributes.Add("name", "region");
regionRadio.Attributes.Add("value", region);
regionRadio.TextAlign = TextAlign.Right;
li.Controls.Add(regionRadio);
radioList.Controls.Add(li);
}

出现了很多我不想要的额外 HTML 标签。我得到的输出为:

<ul id="radioList" class="form_items">    
<li>
<span name="region"><input id="MainContent_contactUs_Radio1" type="radio" name="ctl00$MainContent$contactUs$Radio1" value="Australia">
<label for="MainContent_contactUs_Radio1">Australia</label>
</span>
</li>
<li>
<span name="region"><input id="MainContent_contactUs_Radio2" type="radio" name="ctl00$MainContent$contactUs$Radio2" value="America">
<label for="MainContent_contactUs_Radio2">America</label>
</span>
</li>
</ul>

'Australia/America' 所在的标签会继承与所有标签对齐的样式,从而导致错误的外观。虽然我只是想要

<ul id="radioList" class="form_items">    
<li><input id="MainContent_contactUs_Radio1" type="radio" name="ctl00$MainContent$contactUs$Radio1" value="Australia">"Australia"</li><li><input id="MainContent_contactUs_Radio2" type="radio" name="ctl00$MainContent$contactUs$Radio2" value="America">"America"</li></ul>

最佳答案

如果您使用的是 System.Web.UI.Webcontrols,它将使用 span 呈现您的控件。你可以看到为什么它在跨度之间呈现。

Why does ASP.Net RadioButton and CheckBox render inside a Span?

有两种方法可以克服这个问题。首先,您需要将属性添加到现在不跨度的输入控件,当您直接添加属性时,它会这样做。

请参阅我的博客文章- http://www.dotnetjalps.com/2014/04/aspnet-checkbox-button-attributes-javascript.html

您需要添加如下属性。

myCheckBox.InputAttributes.Add("onblur", "onBlur();");

对于文本对齐和其他内容,我建议您使用 System.Web.UI.HtmlControls,您可以在其中使用 HtmlInputRadioButton 而不是 System.Web.UI.Webcontrols 单选按钮.在这里您还可以非常轻松地管理所有 HTML 属性。

您可以做的另一件事是分别添加标签和 HTMLInputRadioButton,并根据您的要求向标签添加类。

string[] regions = {"Autralia", "Asia", "US"};
foreach (var region in regions)
{
HtmlGenericControl li = new HtmlGenericControl("li");
HtmlInputRadioButton radioButton=new HtmlInputRadioButton
{Value = region,
Name = region};
li.Controls.Add(radioButton);
Label label=new Label {Text = region, CssClass = "YourCSSClass"};
li.Controls.Add(label);
radioList.Controls.Add(li);
}

希望这对css样式有更多的控制

关于c# - 带有动态单选按钮的附加 html 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23128153/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com