Question

I have the following UIHInt based attibute:

[AttributeUsage(AttributeTargets.Property)]
public class DropDownListAttribute : UIHintAttribute, IMetadataAware
{
    public DropDownListAttribute(string selectListName)
        : base(KnownUiHints.DropDown, KnownPresentationLayers.Mvc, selectListName)
    {
        SelectListName = selectListName;
    }

    public string SelectListName { get; set; }

    public void OnMetadataCreated(ModelMetadata metadata)
    {
        metadata.AdditionalValues[KnowMetadataKeys.SelectListName] = SelectListName;
    }
}

It's purpose is to assign a SelectList to a single value view model property to be selected from a list, like this:

public class DemoModel: ViewModel
{
    [Required]
    [DropDownList("LanguageSelect")]
    [Display(Name = "Language")]
    public int? LanguageId { get; set; }

    public SelectList LanguageSelect { get; set; }
}

I have this working now with some very Golbergian machinery and my own metadata provider, but having discovered IMetadataAware.OnMetadataCreated, I feel I can simplify this. Right now I add the SelectListName to the metadata, and then jump through some hoops to a) Get the SelectList into a sort of global dictionary, and b) get the select list out of that dictionary when rendering the dropdown list.

I would like to add the SelectList itself to the model metadata in the attribute, i.e. metadata local to the property the attribute applies to, but how do I access that property or it's containing type?

No correct solution

OTHER TIPS

Sample code to access attributes on Pocos. There is a single or Multi attribute version to look at

sample call to method

var MutliAttributeList = MyStatic.GetPocoMultiAttribute<MyAttribute>(typeof(poco),"AttrName");


 public static UAttribute GetPocoAttribute<TPoco, UAttribute>(string attributeName) {
        var result = typeof (TPoco).GetCustomAttributes(true)
                                   .Where(attribute => attribute.GetType()
                                                                .Name == attributeName)
                                   .Cast<UAttribute>()
                                   .FirstOrDefault();
        return result;
    }

public static IEnumerable<UAttribute> GetPocoMultiAttribute<UAttribute>(Type pocoType, string attributeName) {
        var result = pocoType.GetCustomAttributes(true)
                             .Where(attribute => attribute.GetType()
                                                          .Name == attributeName).Cast<UAttribute>().ToList();
        return result;
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top