Home > programming > LINQ: Expressive Html Tag Building

LINQ: Expressive Html Tag Building

March 3rd, 2009

The following is a repost from ASP.NET Weblogs.  I found it useful so I am posting a copy here for my own reference.

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:

Tag( "a", "The Technical Adventures of Adam Weigert", href => "http://weblogs.asp.net/adweigert/" );
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.”

public string Tag( string tagName, string innerHtml, params Expression<Func<string, string>>[] attributes )
{
    XElement tag = new XElement( XName.Get( tagName, string.Empty ) );
    if ( attributes != null )
    {
        foreach ( var attribute in attributes )
        {
            string attributeName = attribute.Parameters[ 0 ].Name;
            string attributeValue = attribute.Compile()(string.Empty);
             tag.SetAttributeValue( XName.Get( attributeName, string.Empty ), attributeValue );
         }
     }

     if ( !string.IsNullOrEmpty( innerHtml ) )
     {
         tag.Add( XElement.Parse( "<xml>" + innerHtml + "</xml>" ).Nodes() );

     }
     return tag.ToString();
 }

programming ,

  1. No comments yet.
  1. No trackbacks yet.