![](/img/trans.png)
[英]Custom Attributes such as Displayname not listed with GetCustomAttribute
[英]Custom DisplayName
当前,我正在尝试设置属性的动态DisplayName
,但是我无法找到一种方法来获取属性内当前属性的信息。
这是我要实现的目标:
期望的结果
我的属性
public class DisplayNameFromPropertyAttribute : DisplayNameAttribute
{
public DisplayNameFromPropertyAttribute(string propertyName)
: base(GetDisplayName(propertyName))
{
}
private string GetDisplayBame(string propertyName)
{
// Get the value from the given property
}
}
我的模特
我正在尝试将MyDisplayName
的值读取到我的自定义DisplayNameFromProperty
属性中
public class MyAwesomeModel
{
public string MyDisplayName { get; set; }
[Required]
[DisplayNameFromProperty("MyDisplayName")]
public string MyValue { get; set; }
}
我的页面
@Html.LabelFor(model => model.MyValue)
@Html.TextBoxFor(model => model.MyValue)
@Html.ValidationMessageFor(model => model.MyValue)
ComponentModel.DataAnnotations
验证属性应使用我的自定义显示名称 @Html.LabelFor(model => model.MyValue)
应该使用我的自定义显示名称 您可以创建一个cusom HTML扩展方法,使您可以执行@ Html.DictionaryLabelFor(x => x.Property)并将其从字典中提取
public static IHtmlString DictionaryLabelFor<TModel, TValue>(
this HtmlHelper<TModel> html,
Expression<Func<TModel, TValue>> expression, string text = null, string prefix = null)
{
var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
var displayName = metadata.DisplayName;
if (string.IsNullOrWhiteSpace(text))
{
// Your code to get the label via reflection
// of the object
string labelText = "";
return html.Label(prefix + metadata.PropertyName, labelText);
}
else
{
return html.Label(prefix + metadata.PropertyName, text);
}
}
重写此作品上的属性,唯一缺少的是自定义html属性,当我编写它时不需要
验证错误消息略有不同,您应该始终为这些字段编写自定义错误,以便可以在resx中依赖它们,然后查看(prefix + key)的modelstate来获取错误,然后获取的转换后值每个案例。
最好避免覆盖标准HTML调用,因为在其他地方不需要的地方进行过多的调用。
当您能够正常工作并理解它时,错误消息部分将很容易写成您自己,这取决于您要如何对错误进行格式化。 我不是在写它,因为它基本上是在为您做所有事情,如果您不了解它的工作原理,那么在编写更多扩展时会成为SOL
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.