Travails of an ungeeker

Tuesday, March 14, 2006

ASP.NET User Control - accessing InnerHtml

We have a user control using DHTML that displays a button which when clicked renders a floating DIV layer with an image. It is easy to define global string variables that are set from attributes of the user control to pass parameters for the image to show and caption, but then we wanted to inject HTML from between the opening and closing tags of the User control. Creating another element for this was ruled out because this would make the control too hard for our HTML designers to use.

I could not find a solution on the internet and until someone tells me a better one, here is a technique that works:
  1. Define a global property in the User Control with public accessor called Span.
  2. Place an opening and closing SPAN tag between the opening and closing tags of the User Control.
  3. Place your HTML code inside the SPAN.
Now you can access your HTML with Span.InnerHtml. In the case we had we also did the following to inject the user's HTML into the HTML of the User control and did the following.
  1. Add a Literal control to the design view of the User control in the place where the additional HTML should be injected.
  2. In the User control code, override the Render method (Note constructor cannot be used as the control has not been instantiated yet)
  3. Set the literal's Text property to the Span.InnerHtml property. (For gotchas, using Render, you have to check that your span object is not null because it is called several times, and remember to call base.Render(writer);
For the record, Blogger needs to provide some support for quoting code - especially indent formatting. I deleted the code I had from here because I could not make it render in Blogger acceptably. Sorry.