我正在尝试获取与数组中的实例相关联的元数据。我定义了一个HtmlHelper扩展,该扩展在我的视图中调用。我正在尝试创建一个显示模型及其错误消息列表的助手。
@model Domain.Models.Customer
@this.Html.Example(m => m.Orders)
以下是我的助手的此实现
public static class HtmlHelperExtensions
{
public static IHtmlString Example<TModel, TInstance>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TInstance[]>> expression)
{
var instanceProvider = expression.Compile();
var instances = instanceProvider.Invoke(helper.ViewData.Model);
if(instances != null)
{
var properties = typeof (TInstance).GetProperties();
for(var i = 0; i < instances.Length; i++)
{
var instanceExpression = Expression.ArrayIndex(expression.Body, Expression.Constant(i));
foreach(var info in properties)
{
var propertyExpression = Expression.Property(instanceExpression, info);
// How can i get access to the ModelMetadata
ModelMetadata.FromStringExpression(propertyExpression.ToString(), helper.ViewData);
// To get the model state we need the following...
var text = ExpressionHelper.GetExpressionText(Expression.Lambda(propertyExpression));
var fieldName = helper.ViewData.TemplateInfo.GetFullHtmlFieldName(text);
ModelState state;
if(helper.ViewData.ModelState.TryGetValue(fieldName, out state))
{
// Output errors....
}
}
}
}
return MvcHtmlString.Empty;
}
}
使用以下域类
public class Customer
{
public Order[] Orders { get; set; }
}
public class Order
{
public string Description { get; set; }
}
最佳答案
据我所知,它不存在!
ModelMetadata将用于模型的属性,在这种情况下,该属性是数组本身的属性,而不是数组内部的元素。
因此,如果需要ModelMetadata作为数组中的元素,则需要创建Custom Model Metadata Provider,它将获取所需的属性并将其添加到ModelMetadata中,示例指南代码片段
public class ArrayMetadataProvider : 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);
// Add your metadata here
return metadata;
}
}
然后,您需要按以下方式注册此提供程序:
protected void Application_Start()
{
ModelMetadataProviders.Current = new ArrayMetadataProvider();
}