snippets/MvcExtensions.cs 1.0 KB (1014b); Fri, 03 Feb 2012 15:02
´╗┐using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Cselian.Samples.Mvc
{
	public static class HtmlExtensions
	{
		private static readonly object[] NoIndices = new object[] { };

		public static IHtmlString StartTag(this HtmlHelper html, string tagName, object attributes)
		{
			if (attributes == null)
				return new HtmlString(string.Format("<{0}>", tagName));
			var t = attributes.GetType();

			var atts = t.GetProperties().ToDictionary(x => x.Name,
				x => x.GetValue(attributes, NoIndices).ToString());
			if (atts.ContainsKey("CssClass"))
			{
				atts["class"] = atts["CssClass"];
				atts.Remove("CssClass");
			}

			var attVals = atts.Select(x => string.Format("{0}=\"{1}\"", x.Key, x.Value)).ToArray();

			return new HtmlString(string.Format("<{0} {1}>", tagName, string.Join(" ", attVals)));
		}

		public static IHtmlString EndTag(this HtmlHelper html, string tagName)
		{
			return new HtmlString(string.Format("</{0}>", tagName));
		}
	}
}