开发者

Template that shows properties with certain attributes?

I am creating an object template that will show only a few fields of a model class, to be used as a summary of the object. I created a Summary attribute and flagged certain fields with that attribute. I can't figure out how to actually determine if the property has that attribute though, because in the object template I don't have the actual property, but instead a ModelMetadata instead. How can I determine if the property has the Summary attribute in the object template?

public class Car
{
  [Key]
  public int CarKey { get; set;}

  [Summary]
  public string Color { get; set;}

  public string EngineSize { get; set;}

  [Summary]
  public string Model { get; set;}    

  public int NumberOfDoors

}

This is my object templatE:

@if (Model == null) {
    <text>@ViewData.ModelMetadata.NullDisplayText</text>
} else if (ViewData.TemplateInfo.TemplateDepth > 1) {
    <text>@ViewData.ModelMetadata.SimpleDisplayText</text>
} else {
    <table cellpadding="0" cellspacing="0" border="0">
    @foreach (var prop in ViewData.ModelMetadata.Properties.Where(pm => pm.ShowForDisplay && !ViewData.TemplateInfo.Visited(pm))) {

      if(prop./******************** what goes here ************************/
        if (prop.HideSurroundingHtml) {
            <text>@Html.Display(prop.PropertyName)</text>
        } else {
            <tr>
                <td>
                    <div class="display-label" style="text-align: right;">
                        @prop.GetDisplayName()
                    </div>
                </td>
                <td>
                    <div class="display-field">
         开发者_如何学C               @Html.Display(prop.PropertyName)
                    </div>
                </td>
            </tr>
        }
    }
    </table>
}


The best way to achieve what you want is by changing your SummaryAttribute to implement IMetadataAware. This is an extensibility mechanism that allows metadata attributes to provide additional information to the ModelMetadata object:

public void OnMetadataCreated(ModelMetadata metadata) {
    if (metadata == null) {
        throw new ArgumentNullException("metadata");
    }

    metadata.AdditionalValues["Summary"] = true;
}

then your property check could be

if(prop.AdditionalValues.ContainsKey("Summary"))

If you cannot change the implementation of SummaryAttribute or derive from it, then you could consider using the built-in AdditionalMetadataAttribute

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜