Convert ASP.NET PlaceHolder to HTML tag with attributes


/ Published in: C#
Save to your folder(s)

## Markup ##
_Using square [ ] brackets for compatibility with Snipplr comment form_

[asp:PlaceHolder ID="StuffHolder" runat="server" ]
<p>Some stuff in here</p>
[/asp:PlaceHolder]

## Code Behind ##

HtmlAttr[] attributes = {
new HtmlAttr("id","stuff"),
new HtmlAttr("class","container")
};
PlaceHolderToTag(StuffHolder, "div", attributes);

## Result ##

[div id="stuff" class="container"]
<p>Some stuff in here</p>
[/div]

### Notes:

Useful with the "Visible" property on the placeholder, and facilites
programmically setting IDs on DIVs (can set id based on some item name)


Copy this code and paste it in your HTML
  1. public static void PlaceHolderToTag(PlaceHolder holder, string tag, HtmlAttr[] attributes) {
  2.  
  3. if (!holder.Visible) { return; }
  4.  
  5. //Init new control to use as tag
  6. HtmlControl newControl = new HtmlGenericControl(tag);
  7.  
  8. //Add attributes
  9. foreach (HtmlAttr attr in attributes) {
  10. newControl.Attributes.Add(attr.Key, attr.Value);
  11. }
  12.  
  13. //Add all the place holder's controls
  14. foreach (Control ctrl in holder.Controls) {
  15. newControl.Controls.Add(ctrl);
  16. }
  17.  
  18. holder.Parent.Controls.Add(newControl);
  19. holder.Controls.Clear();
  20. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.