Using ModelMetadata how do you call DisplayFor and have the metadata used
This question is based on using the Asp.Net MVC tabular layout display template from Phil Haack http://haacked.com/archive/2010/05/05/asp-net-mvc-tabular-display-template.aspx
The problem is in the Html.DisplayFor(m => propertyMetadata.Model). This displays the data from the property just fine, however it doesn't use any of the data annotations that may be present. I'm mostly thinking the DataType annotation here for example DataType.Date. This annotation correctly outputs a short date when used with DisplayFor, but not when the property is reflected from the ModelMetadata as in this example. (It shows a full DateTime)
<% for(int i = 0; i < Model.Count; i++) {
var itemMD = ModelMetadata.FromLambdaExpression(m => m[i], ViewData); %>
<tr>
<开发者_运维百科;% foreach(var property in properties) { %>
<td>
<% var propertyMetadata = itemMD.Properties
.Single(m => m.PropertyName == property.PropertyName); %>
<%= Html.DisplayFor(m => propertyMetadata.Model) %>
</td>
<% } %>
</tr>
An example model would be an
public class TableModel
{
[UIHint("Table")]
public PeriodModel[] Periods { get; set; }
}
public class PeriodModel
{
[DisplayName("Description")]
public string Description { get; set; }
[DisplayName("Date From")]
[DataType(DataType.Date)]
public DateTime DateFrom { get; set; }
[DisplayName("Date To")]
[DataType(DataType.Date)]
public DateTime DateTo { get; set; }
}
So how would this be changed to get the full metadata behaviour of DisplayFor?
Seems this is a simple one, you just have to change:
Html.DisplayFor(m => propertyMetadata.Model)
to
Html.DisplayFor(m => propertyMetadata.Model, propertyMetadata.TemplateHint)
I've been struggling with this myself for a few hours and this is the only hit I found on Google. But the answer is wrong.
propertyMetadata.TemplateHint
is always null
in my case.
But this works:
Html.DisplayFor(m => propertyMetadata.Model, propertyMetadata.DataTypeName)
you can check @Html.ValueFor(m => propertyMetdata.Model)
instead of DisplayFor
.
精彩评论