带动态单选按钮的其他html标签

时间:2014-04-17 08:26:19

标签: c# asp.net css radio-button asp.net-controls

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

Regions.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>

澳大利亚/美国&#39;即将到来会导致错误的外观,继承与所有标签对齐的样式。 虽然我只想要

<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>

2 个答案:

答案 0 :(得分:1)

如果您使用的是System.Web.UI.Webcontrols,它将使用span渲染您的控件。你可以看到为什么它在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();");

对于text align和其他东西我建议你使用 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样式有更多控制

答案 1 :(得分:0)

我认为text-align设置单选按钮在其容器中的水平位置。

所以,检查你的容器是否包裹到你的单选按钮。