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 )
3: XElement tag = new XElement( XName.Get( tagName, string.Empty ) );
5: if ( attributes != null )
7: foreach ( var attribute in attributes )
9: string attributeName = attribute.Parameters[ 0 ].Name;
10: string attributeValue = attribute.Compile()(string.Empty);
12: tag.SetAttributeValue( XName.Get( attributeName, string.Empty ), attributeValue );
16: if ( !string.IsNullOrEmpty( innerHtml ) )
18: tag.Add( XElement.Parse( "<xml>" + innerHtml + "</xml>" ).Nodes() );
21: return tag.ToString();
Update: Used XElement instead, and better innerHtml handling. Thanks to everyone that helped improve this method.