How to get values out of object HtmlAttributes
you can transform the object htmlAttirbutes to an attribute/value string representation like this :
var htmlAttributes = new { id="myid", @class="myclass" };
string string_htmlAttributes = "";
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(htmlAttributes))
{
string_htmlAttributes += string.Format("{0}=\"{1}\" ", property.Name.Replace('_', '-'), HttpUtility.HtmlAttributeEncode(property.GetValue(htmlAttributes).ToString()));
}
PropertyDescriptor
belong to the class System.ComponentModel
I usually do something like this:
public static string Label(this HtmlHelper htmlHelper, string forName, string labelText, object htmlAttributes)
{
return Label(htmlHelper, forName, labelText, new RouteValueDictionary(htmlAttributes));
}
public static string Label(this HtmlHelper htmlHelper, string forName, string labelText,
IDictionary<string, object> htmlAttributes)
{
// Get the id
if (htmlAttributes.ContainsKey("Id"))
{
string id = htmlAttributes["Id"] as string;
}
TagBuilder tagBuilder = new TagBuilder("label");
tagBuilder.MergeAttributes(htmlAttributes);
tagBuilder.MergeAttribute("for", forName, true);
tagBuilder.SetInnerText(labelText);
return tagBuilder.ToString();
}
I suggest you to download the ASP.NET MVC source from the codeplex and take a look at the built in html helpers.