CustomAttribute反映了html属性MVC5
希望找到一种方法,当在MVC5中使用Custom属性或者更喜欢RegularExpressionAttribute修饰模型中的属性时,html控件将它包含为控件的另一个属性。 例如
class CoolModel { [CustomHtmlAttribute("hello")] public string CoolValue {get;set;} }
输出…
或类似的东西。 因此,对于RegularExpressionAttribute,pattern属性将非常棒。
class CoolModel { [RegularExpressionAttribute("/d")] public string CoolValue {get;set;} }
输出…
我需要此输出而不启用Javascript不显眼的选项。 所以我想在某种方式中指定模型中的一些属性,这些属性可以下推到视图中。 不确定数据注释提供程序是否可以执行此任务。 不确定是否可以扩展Helper以获得此结果。
感谢帮助。
- Automapper,Mapper未初始化。 使用正确的配置调用初始化
- 在没有属性的类上全局使用JsonConverter
- LInkedIn oAuth2请求令牌400错误请求
- 在控制器post方法中,MVC 4模型中的提交表单为空
- @ Html.ValueFor(x => x.PropertyName)和@ Model.PropertyName之间的区别是什么?
如果使用带有重载的标准帮助程序来添加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(this HtmlHelper helper, Expression> 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属性。