How to access C # model attribute in editor

I have a model as shown below:

public class CreateStockcheckJobModel
{
    [Engineer(true)]
    public EngineerModel Engineer { get; set; }
}

I pass the property Engineerin View<CreateStockcheckJobModel>with Html.EditorFor(m => m.Engineer, "EngineerEditor").

How do I access a value in an attribute Engineer(in this case true) from 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>
<% } %>

, , , EngineerModel, Engineer CreateStockcheckJobModel. PropertyInfo, , , , . CreateStockcheckJobModel, , EngineerModel ( true, False > ).

+5
2

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, .

, .

+7

. , IMetadataAware, , . , .

. , .

EngineerAttribute Engineer:

PropertyInfo pi = Model.GetType().GetProperty("Engineer");
EngineerAttribute a =
    System.Attribute.GetCustomAttribute(pi, typeof(EngineerAttribute));

, [Engineer(true)]:

var t = Model.GetType();
var engineerProperties =
    from p in t.GetProperties()
    let ca = System.Attribute.GetCustomAttribute(p, typeof(EngineerAttribute))
    where ca != null && ca.BooleanProperty == true
    select p;

, EditorFor, , :

Html.EditorFor(m => m.Engineer, new { IsEngineer = isEngineer });
+1

All Articles