无法在 MVC3 HTML Helper 中获取自定义属性值
我已经使用需要模型属性中的属性值的方法扩展了 HTML 帮助器。所以我定义了一个自定义属性。
public class ChangeLogFieldAttribute : Attribute {
public string FieldName { get; set; }
}
它在我的模型中是这样使用的。
[Display(Name = "Style")]
[ChangeLogField(FieldName = "styleid")]
public string Style { get; set; }
在我的帮助器方法中,如果属性用于属性,我将使用以下代码来获取属性的 FieldName 值。
var itemName = ((MemberExpression)ex.Body).Member.Name;
var containerType = html.ViewData.ModelMetadata.ContainerType;
var attribute = ((ChangeLogFieldAttribute[])containerType.GetProperty(html.ViewData.ModelMetadata.PropertyName).GetCustomAttributes(typeof(ChangeLogFieldAttribute), false)).FirstOrDefault();
if (attribute != null) {
itemName = attribute.FieldName;
}
但是,当我到达此代码时,我收到一个异常,因为 containerType 为 null。
我不确定我所做的是否正确,但我从大约 4 个不同的来源中获取了这一步。如果您可以建议解决我的问题或替代方案,我将不胜感激。
谢谢。
更新解决方案
我使用了 Darin Dimitrov 的解决方案,尽管我必须对其进行一些调整。这是我添加的内容。我必须检查属性元数据是否存在,一切都很好。
var fieldName = ((MemberExpression)ex.Body).Member.Name;
var metadata = ModelMetadata.FromLambdaExpression(ex, html.ViewData);
if (metadata.AdditionalValues.ContainsKey("fieldName")) {
fieldName = (string)metadata.AdditionalValues["fieldName"];
}
I've extended the HTML helper with a method that needs an attribute value from the property of the model. So I've defined a custom attribute as such.
public class ChangeLogFieldAttribute : Attribute {
public string FieldName { get; set; }
}
It's used like this in my model.
[Display(Name = "Style")]
[ChangeLogField(FieldName = "styleid")]
public string Style { get; set; }
In my helper method, I've got the following code to get the FieldName value of my attribute, if the attribute is used for the property.
var itemName = ((MemberExpression)ex.Body).Member.Name;
var containerType = html.ViewData.ModelMetadata.ContainerType;
var attribute = ((ChangeLogFieldAttribute[])containerType.GetProperty(html.ViewData.ModelMetadata.PropertyName).GetCustomAttributes(typeof(ChangeLogFieldAttribute), false)).FirstOrDefault();
if (attribute != null) {
itemName = attribute.FieldName;
}
However, when I reach this code, I get an exception because the containerType is null.
I'm not sure if I'm doing any of this correct, but I pulled from about 4 different sources to get this far. If you could suggest a fix to my problem or an alternative, I'd be grateful.
Thanks.
UPDATE WITH SOLUTION
I used Darin Dimitrov's solution, although I had to tweak it some. Here is what I added. I had to check for the existence of the attribute metatdata and all was good.
var fieldName = ((MemberExpression)ex.Body).Member.Name;
var metadata = ModelMetadata.FromLambdaExpression(ex, html.ViewData);
if (metadata.AdditionalValues.ContainsKey("fieldName")) {
fieldName = (string)metadata.AdditionalValues["fieldName"];
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使属性元数据感知:
然后在助手内部:
You could make the attribute metadata aware:
and then inside the helper: