我使用的两种方法(Chtiwi马利克和rrejc)的混合早先提出,它的工作很好。
用这种方法,它会将data_id
转换为data-id
。它也会覆盖你之前设置的默认属性值。
using System.ComponentModel;
...
public static MvcHtmlString RequiredLabelFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> 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());
}
请注意有关覆盖在foreach中的代码中具有默认值的属性的注释。
事实证明,您的示例比源代码更丰富。我无法弄清楚源代码是如何工作的,因为它是一个IDictionary(就像你的标签所做的那样),但我试图将它传递给匿名对象。一旦我看到你将它转换为RouteValueDictionary更有意义。 – 2009-10-07 20:46:55
这似乎不适用于像data_bind这样的属性 – SimonGates 2013-05-22 12:05:50