ASP.NET MVC 3 , IMetadataAware EngineerAttribute:
public class EngineerAttribute : Attribute, IMetadataAware
{
public EngineerAttribute(bool isFoo)
{
IsFoo = isFoo;
}
public bool IsFoo { get; private set; }
public void OnMetadataCreated(ModelMetadata metadata)
{
metadata.AdditionalValues["IsFoo"] = IsFoo;
}
}
:
<%@ Control Language="C#" Inherits="ViewUserControl<EngineerModel>" %>
<%
var isFoo = (bool)ViewData.ModelMetadata.AdditionalValues["IsFoo"];
%>
<% if (isFoo) { %>
<p>Render one thing</p>
<% } else { %>
<p>Render another thing</p>
<% } %>
, ASP.NET MVC 2. , :
public class MyMetadataProvider : DataAnnotationsModelMetadataProvider
{
protected override ModelMetadata CreateMetadata(
IEnumerable<Attribute> attributes,
Type containerType,
Func<object> modelAccessor,
Type modelType,
string propertyName
)
{
var metadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);
var engineer = attributes.OfType<EngineerAttribute>().FirstOrDefault();
if (engineer != null)
{
metadata.AdditionalValues["IsFoo"] = engineer.IsFoo;
}
return metadata;
}
}
Application_Start, :
ModelMetadataProviders.Current = new MyMetadataProvider();
, , ViewData.ModelMetadata.AdditionalValues["IsFoo"]. , AdditionalValues, .
, .