StringLengthAttribute

时间:2010-11-02 12:44:06

标签: asp.net-mvc modelmetadata

我正在使用Asp.Net MVC 2,并尝试迭代元数据以向网格列添加输入控件。默认的modelmetadata提供程序不会填充大多数属性,如DisplayAttribute,StringLength属性等。

1-我认为这些属性将在MVC3中得到支持,对吧?

2-是否有一个我可以使用的自定义提供程序,直到MVC3出来,我记得看到一个自定义元数据提供程序(认为它在MVCContrib中)但在那里找不到,有人知道在哪里可以找到支持这个属性的metadataprovider ?

1 个答案:

答案 0 :(得分:0)

我写了一个提供程序来处理比标准提供程序更多的属性。这是个主意:

/// <summary>
/// Adds support for data annotation attributes omitted from DataAnnotationsModelMetadataProvider
/// </summary>
public class ExtendedDataAnnotationsModelMetadataProvider : DataAnnotationsModelMetadataProvider
{
    protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
    {
        var result = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);

        DisplayAttribute da = attributes.OfType<DisplayAttribute>().FirstOrDefault();
        if (da != null)
        {
            var autoGenerate = da.GetAutoGenerateFilter();
            if (autoGenerate.HasValue)
            {
                result.AdditionalValues[AdditionalValuesKeys.AutoGenerateFilter] = autoGenerate.Value;
            }
            var groupName = da.GroupName;
            if (!string.IsNullOrEmpty(groupName))
            {
                result.AdditionalValues[AdditionalValuesKeys.GroupName] = groupName;
            }
            if (!string.IsNullOrEmpty(da.Prompt))
            {
                result.Watermark = da.Prompt;
            }
        }

        DisplayColumnAttribute dc = attributes.OfType<DisplayColumnAttribute>().FirstOrDefault();
        if (dc != null)
        {
            var sc = dc.SortColumn;
            if (!string.IsNullOrEmpty(sc))
            {
                result.AdditionalValues[AdditionalValuesKeys.SortColumnName] = sc;
                if (dc.SortDescending)
                {
                    result.AdditionalValues[AdditionalValuesKeys.SortDescending] = true;
                }
            }
        }

        StringLengthAttribute sla = attributes.OfType<StringLengthAttribute>().FirstOrDefault();
        if (sla != null)
        {
            result.AdditionalValues[AdditionalValuesKeys.MaximumStringLength] = sla.MaximumLength;
        }

        return result;
    }
}

当然,MVC的默认模板实际上并没有对该信息做任何事情。你必须customize them yourself