Question

I am using Asp.Net MVC 2, and trying to iterate through the metadata to add input controls to grid columns. Most attributes like DisplayAttribute, StringLength attribute, etc are not populated by the default modelmetadata provider.

1- I think these attributes are going to be supported in MVC3, right?

2- Is there a custom provider that I can use till MVC3 is out, I remember seeing a custom metadata provider (thought it was in MVCContrib) but could not find it there, anyone knows where to find the metadataprovider supporting this attributes?

Was it helpful?

Solution

I wrote a provider to handle more attributes than the standard provider does. Here's the idea:

/// <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;
    }
}

Naturally, the default templates with MVC don't actually do anything with that info. You have to customize them yourself.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top