我正在尝试获取与数组中的实例关联的元数据。我已经定义了一个在我的视图中调用的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; }
}
答案 0 :(得分:0)
据我所知,它不存在!
ModelMetadata将用于Model的Properties,在这种情况下,数组本身的属性不是数组中的元素。
因此,如果您需要ModelMetadata用于数组中的元素,您将需要创建自定义模型元数据提供程序,它将获取您需要的属性并将它们添加到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();
}