问题
I have a server control that I have written, which generally works fine. However when I add in the highlighted line, it adds in not one but two <br />
elements, which is not what I am after.
mounting=new DropDownLabel();
mounting.ID="mountTypeList";
mounting.Attributes.Add("class", "mounting");
mounting.Values=Configuration.MountTypes.GetConfiguration().Options;
mounting.Enabled=Utilities.UserType == UserType.Admin;
mounting.Value=value.Reference;
td1.Controls.Add(mounting);
**td1.Controls.Add(new HtmlGenericControl("br"));**
var span=new HtmlGenericControl("span");
span.Attributes.Add("class", "mountDescription");
span.ID="mountDescription";
td1.Controls.Add(span);
Any thoughts on what I am doing wrong?
ETA:
I have resolved the situation by adding the br using jquery, which I am using there anyway. But the behaviour I saw is surely wrong. If I add an element, it should add that element, not twice that element.
回答1:
HtmlGenericControl
will generate the with the opening and closing tags <br>
and </br>
instead you could use new LiteralControl("<br/>")
which should do what you desire.
EDIT
To get around this you will need your own implementation of the HtmlGenericControl
and extend it for such cases which don't have opening and closing tags associated.
public class HtmlGenericSelfClosing : HtmlGenericControl
{
public HtmlGenericSelfClosing()
: base()
{
}
public HtmlGenericSelfClosing(string tag)
: base(tag)
{
}
protected override void Render(HtmlTextWriter writer)
{
writer.Write(HtmlTextWriter.TagLeftChar + this.TagName);
Attributes.Render(writer);
writer.Write(HtmlTextWriter.SelfClosingTagEnd);
}
public override ControlCollection Controls
{
get { throw new Exception("Self-closing tag cannot have child controls"); }
}
public override string InnerHtml
{
get { return String.Empty; }
set { throw new Exception("Self-closing tag cannot have inner content"); }
}
public override string InnerText
{
get { return String.Empty; }
set { throw new Exception("Self-closing tag cannot have inner content"); }
}
}
Found Here
来源:https://stackoverflow.com/questions/7526985/server-control-behaving-oddly