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"];
}
You could make the attribute metadata aware:
public class ChangeLogFieldAttribute : Attribute, IMetadataAware
{
public string FieldName { get; set; }
public void OnMetadataCreated(ModelMetadata metadata)
{
metadata.AdditionalValues["fieldName"] = FieldName;
}
}
and then inside the helper:
var metadata = ModelMetadata.FromLambdaExpression(ex, htmlHelper.ViewData);
var fieldName = metadata.AdditionalValues["fieldName"];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With