Example of using AdditionalMetadata in MVC 3
In asp.net MVC 3 there is a new attribute that allows us to pass additional Meta Data to our views e.g.
[Required]
[AdditionalMetadata("Tooltip", "The title of the item")]
public string Title { get; set; }
The question is, how do I actually make use of this information in my view? I thought that perhaps it would render out the data as html 5 data attributes but this is not the case.
开发者_如何学运维A simple example would be much appreciated.
According to the documentation:
You can use the AdditionalMetadataAttribute class to populate the ModelMetadata.AdditionalValues dictionary for a model property.
...
This metadata is made available to any display or editor template when a product view model is rendered. It is up to you as application developer to interpret the metadata information.
So let's make use of it in the view:
<h2>
@ModelMetadata.FromLambdaExpression(x => x.Title, ViewData).AdditionalValues["Tooltip"]
</h2>
example in a template:
Object optionlabelOverride;
ViewData.ModelMetadata.AdditionalValues.TryGetValue("OptionLabelText", out optionLabelOverride);
the variable you are reading must be an object and then you can cast it. Everything you set in the model is available as ViewData.
精彩评论