【问题标题】:How to I find the target property of a UIHInt attribute?如何找到 UIHInt 属性的目标属性?
【发布时间】:2013-02-28 11:21:45
【问题描述】:

我有以下基于 UIHInt 的属性:

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

其目的是将 SelectList 分配给要从列表中选择的单值视图模型属性,如下所示:

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

    public SelectList LanguageSelect { get; set; }
}

我现在正在使用一些非常 Golbergian 的机器和我自己的元数据提供程序,但是在发现 IMetadataAware.OnMetadataCreated 之后,我觉得我可以简化它。现在我将SelectListName 添加到元数据中,然后跳过一些步骤a)将 SelectList 放入某种全局字典中,b)在呈现下拉列表时从该字典中取出选择列表。

我想将 SelectList 本身添加到属性中的模型元数据中,即属性适用于属性的本地元数据,但我如何访问该属性或它包含类型?

【问题讨论】:

  • 您在视图中使用什么 HtmlHelper 方法来输出列表?

标签: entity-framework entity-framework-5 data-annotations asp.net-mvc-uihint


【解决方案1】:

访问 Pocos 属性的示例代码。 有单属性或多属性版本可供查看

方法调用示例

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

【讨论】:

    猜你喜欢
    • 2011-09-14
    • 1970-01-01
    • 1970-01-01
    • 2018-04-09
    • 2020-03-04
    • 1970-01-01
    • 1970-01-01
    • 2015-11-09
    • 1970-01-01
    相关资源
    最近更新 更多