希望找到一种方法,当在MVC5中使用Custom属性或者更喜欢RegularExpressionAttribute修饰模型中的属性时,html控件将其包含为控件的另一个属性。 E.g。
class CoolModel {
[CustomHtmlAttribute("hello")]
public string CoolValue {get;set;}
}
...输出
<input type="text" customhtml="hello" />
或类似的东西。因此,对于RegularExpressionAttribute,pattern属性将非常棒。
class CoolModel {
[RegularExpressionAttribute("/d")]
public string CoolValue {get;set;}
}
...输出
<input type="text" pattern="/d" />
我需要此输出而不启用Javascript unobtrusive选项。因此,我想以某种方式在模型中指定一些属性,将其推向视图。不确定数据注释提供程序是否可以执行此任务。不确定是否可以扩展Helper以获得此结果。
非常感谢帮助。
答案 0 :(得分:4)
如果使用带有重载的标准帮助程序来添加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属性。