I have a model like below:
public class CreateStockcheckJobModel
{
[Engineer(true)]
public EngineerModel Engineer { get; set; }
}
I’m rendering the Engineer property in a View<CreateStockcheckJobModel> using Html.EditorFor(m => m.Engineer, "EngineerEditor").
How do I access the value in the Engineer attribute (in this case true) from within the code in my partial view (EngineerEditor.ascx)?
Below is my editor code
<%@ Control Language="C#" Inherits="ViewUserControl<EngineerModel>" %>
<% if (PropertyImRenderingHasAttributeWithTrueBooleanValue) // What goes here?
{ %>
<p>Render one thing</p>
<% }
else
{ %>
<p>Render another thing</p>
<% } %>
I’m aware of reflection, however i’m unsure how to use it as the attribute isn’t added to the EngineerModel class it’s added to the Engineer property of the CreateStockcheckJobModel class. If i could get the PropertyInfo that I’m rendering from the editor code then I’d be sorted, but I don’t know how to get that information. If I go down the route of enumerate all properties in the CreateStockcheckJobModel class then I’m going to get issues if I have more than one EngineerModel property (one might have the attribute with True, another might have False).
This could be done easily in ASP.NET MVC 3 and later by implementing the
IMetadataAwareinterface on your customEngineerAttribute:and then inside the template:
Unfortunately this interface doesn’t exist in ASP.NET MVC 2. To achieve the same functionality you could write a custom metadata provider:
that you will register in your
Application_Startin order to replace the default one:And now you could access this metadata in your template the same way as I showed earlier, using
ViewData.ModelMetadata.AdditionalValues["IsFoo"]. Obviously you could put an arbitrarily complex object inside theAdditionalValuesproperty, not just booleans.Also you might find the following article useful about metadata.