Posted By

jasonseney on 05/14/09


Tagged

html c aspnet placeholder


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

umang_nine
derekholmes


Convert ASP.NET PlaceHolder to HTML tag with attributes


 / Published in: C#
 

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)

  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  

You need to login to post a comment.