获取特定实例的ModelMetadata

本文关键字:ModelMetadata 实例 获取 | 更新日期: 2023-09-27 18:14:46

我试图获得与数组中的实例关联的元数据。我已经定义了一个在我的视图中调用的HtmlHelper扩展。我正在尝试创建一个显示模型列表及其错误消息的帮助器。

@model Domain.Models.Customer
@this.Html.Example(m => m.Orders)
下面是我的helper 的实现
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将用于模型的属性,在这种情况下是数组本身的属性,而不是数组中的元素。

因此,如果您需要为数组中的元素提供ModelMetadata,您将需要创建Custom ModelMetadata 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();
    }