如果使用带有重载的标准助手来添加 html 属性是不可接受的,那么您可以创建一个属性实现IMetadataAware
将属性添加到metadata.AdditionalValues
然后可以在自定义 html 帮助程序中使用它。一个简单的例子可能是
[AttributeUsage(AttributeTargets.Property)]
public class CustomHtmlAttribute : Attribute, IMetadataAware
{
public static string ValueKey
{
get { return "Value"; }
}
public string Value { get; set; }
public void OnMetadataCreated(ModelMetadata metadata)
{
if (Value != null)
{
metadata.AdditionalValues[ValueKey] = Value;
}
}
}
并创建一个助手来渲染文本框(此处仅显示一个重载)
public static MvcHtmlString CustomHtmlTextBoxFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression)
{
ModelMetadata metaData = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
object attributes = null;
if (metaData.AdditionalValues.ContainsKey(ValueKey))
{
attributes = new { customhtml = (string)metaData.AdditionalValues[ValueKey] };
}
return InputExtensions.TextBoxFor(helper, expression, attributes);
}
并将其用作
[CustomHtml(Value = "hello")]
public string CoolValue { get; set; }
并在视图中
@Html.CustomHtmlTextBoxFor(m => m.CoolValue)
为了使其更加灵活,您可以向属性添加更多属性,以便可以将其应用为
[CustomHtml(Value = "hello", Pattern="/d")]
public string CoolValue { get; set; }
并修改助手以呈现您定义的所有 html 属性。