In asp.net mvc I always see the built in html helpers they always have object htmlAttirbutes.
Then I usually do new {@id = \"test\", @class=\"myClass\"}.
How do
I use a mix of both methods (Chtiwi Malek and rrejc) proposed earlier and it works great.
With this method, it will convert data_id
to data-id
. It will also overwrite default attribute values you have set earlier.
using System.ComponentModel;
...
public static MvcHtmlString RequiredLabelFor(this HtmlHelper helper, Expression> expression, object htmlAttributes)
{
var metaData = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
string htmlFieldName = ExpressionHelper.GetExpressionText(expression);
string labelText = metaData.DisplayName ?? metaData.PropertyName ?? htmlFieldName.Split('.').Last();
if (String.IsNullOrEmpty(labelText))
return MvcHtmlString.Empty;
var label = new TagBuilder("label");
label.Attributes.Add("for", helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName));
foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(htmlAttributes))
{
// By adding the 'true' as the third parameter, you can overwrite whatever default attribute you have set earlier.
label.MergeAttribute(prop.Name.Replace('_', '-'), prop.GetValue(htmlAttributes).ToString(), true);
}
label.InnerHtml = labelText;
return MvcHtmlString.Create(label.ToString());
}
Note the comment about overwriting an attribute that has a default value in your code in the foreach.