ASP.NET Weblogs

Welcome to ASP.NET Weblogs Sign in | Join | Help
in Search

The Technical Adventures of Adam Weigert

January 2009 - Posts

  • LINQ: Expressive Html Tag Building

    I hate building HTML tags in code, but it needs to be done. I just wanted to make it a little cleaner. So I came up with this method that utilizes LINQ expressions to generate the attributes for the tag. This is really only clean with simple tags, but I use it with my other tag building methods to keep them clean as well. I've seen others look for something like this and thought it'd be helpful posting it here. I haven't deeply tested this code but it shows the general concept and I'm sure it needs cleaned up a little. The following is an example calling the Tag method:

       1:  Tag( "a", "The Technical Adventures of Adam Weigert", href => "http://weblogs.asp.net/adweigert/" );
       2:  Tag( "div", "LINQ Expressions Rock", style => "font-size: 250%; font-weight: bold;", id => "title" );

    This is the actual method, I love how simple the LINQ expression makes building the attributes.

       1:  public string Tag( string tagName, string innerHtml, params Expression<Func<string, string>>[] attributes )
       2:  {
       3:      XElement tag = new XElement( XName.Get( tagName, string.Empty ) );
       4:      
       5:      if ( attributes != null )
       6:      {
       7:          foreach ( var attribute in attributes )
       8:          {
       9:              string attributeName = attribute.Parameters[ 0 ].Name;
      10:              string attributeValue = attribute.Compile()(string.Empty);
      11:   
      12:              tag.SetAttributeValue( XName.Get( attributeName, string.Empty ), attributeValue );
      13:          }
      14:      }
      15:   
      16:      if ( !string.IsNullOrEmpty( innerHtml ) )
      17:      {
      18:          tag.Add( XElement.Parse( "<xml>" + innerHtml + "</xml>" ).Nodes() );
      19:      }
      20:   
      21:      return tag.ToString();
      22:  }

    Update: Used XElement instead, and better innerHtml handling. Thanks to everyone that helped improve this method.

More Posts