Custom Control Block elements in the ASP.NET Designer
Getting an ASP.NET control to display properly in the designer can be a bit of the chore because the designer doesn’t do real well when it comes to rendering controls based on block tags, like <div> or <table>. The VS.NET designer renders controls into a block that appears to be a self-sizing <span> tag or equivalent, so if you have block content the designer usually mucks up the display.
For example, here’s a control that renders as a DIV in the designer:

The control should not show the percentage tag on the same block line as the Progress control. The code that generates this uses a DIV tag with a bunch of attributes. It doesn’t matter whether the output from this is generated in the Render() method of the control or a separate ControlDesigner the inline behavior is the same.
This is pretty annoying in many cases because it throws off your design. In some cases you may get around this by explicitly adding HTML <br /> tags into your markup, which will do the right thing both at design time and runtime, but in some cases a break is just not what you want to put into the HTML.
So the workaround I came up for this behavior is to wrap the control into another <div> tag and force it to 100% for the designer output:
protected override void Render(HtmlTextWriter writer)
{
if (this.DesignMode)
writer.Write("<div style='width:100%'>");
writer.Write("<div class='" + this.CssClass + "' style='height:" + this.Height.ToString() + ";width:" + this.Width.ToString() +
";text-align:left;padding:" + this.CellPadding.ToString() + "'>");
// … render your content
writer.Write("</div>\r\n");
if (this.DesignMode)
writer.Write("</div>");
}
The result looks like this in the designer:

which is a much closer match to what the control will actually render at runtime. Note that now block operations like centering also work properly because the control is no tightly bordered by the container.
Not quite as smooth as I would have hoped, but it works. Maybe there’s a better way to force this but I couldn’t find it.
Other Posts you might also like
- Adding minimal OWIN Identity Authentication to an Existing ASP.NET MVC Application
- Resolving Paths To Server Relative Paths in .NET Code
- Map Physical Paths with an HttpContext.MapPath() Extension Method in ASP.NET
- Back to Basics: Rewriting a URL in ASP.NET Core
- Getting the Client IP Address in ASP.NET Core
The Voices of Reason
# re: Custom Control Block elements in the ASP.NET Designer
I guess don't worry about it in this version, but when the new editor comes this would be nice to get fixed. <div> and <table> etc. tags should respect their display:block status.
I've fought this on a number of occasions, but never really followed this through until the other day. The workaround works I suppose, but it shouldn't be necessary.
# re: Custom Control Block elements in the ASP.NET Designer