希望找到一种方法,当在 MVC5 中使用自定义属性或最好使用 RegularExpressionAttribute 装饰模型中的属性时,html 控件将其作为控件的另一个属性包含。例如
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 不显眼选项。因此,我正在考虑以某种方式指定模型中的某些属性,并将其下推到 View 。不确定数据注释提供者是否可以完成这项工作。不确定是否可以扩展 Helper 来获得此结果。
感谢帮助。
最佳答案
如果使用带有重载的标准助手来添加 html 属性是 Not Acceptable ,那么您可以创建一个属性实现 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; }
并在 View 中
@Html.CustomHtmlTextBoxFor(m => m.CoolValue)
为了使其更加灵活,您可以向属性添加更多属性,以便将其应用为
[CustomHtml(Value = "hello", Pattern="/d")]
public string CoolValue { get; set; }
并修改帮助器以呈现您定义的所有 html 属性。
关于c# - CustomAttribute反射(reflect)html属性MVC5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26519493/