无法访问ASP MVC核心编辑器模板

时间:2018-05-20 21:51:57

标签: asp.net-mvc asp.net-core

我有以下自定义属性

[AttributeUsageAttribute(AttributeTargets.Property, AllowMultiple = false)]
public class ColumnAttribute : Attribute
{

    public ColumnAttribute(int size)
    {
        Class = "col-md-" + size.ToString();
    }

    public string Class { get; set; }
}

一个通用的编辑器模板,它遍历模型中的所有属性并吐出所需的标记:

@model dynamic

@foreach (var prop in ViewData.ModelMetadata.Properties)
{
    if (prop.TemplateHint == "HiddenInput")
    {
        @Html.Hidden(prop.PropertyName)
    }
    else
    {

      //Access properties attribute and use it to populate class

       <div class="">

       @Html.Editor(prop.PropertyName)

      </div>
    }
}

我试图在具有它的属性上访问自定义ColumnAttribute,以便我可以将给定的类添加到包装div的编辑器中。

我试过了:

var Member = ViewData.ModelMetadata.ContainerType.GetMember(ViewData.ModelMetadata.PropertyName);
var attr = Member[0].GetCustomAttribute<ColumnAttribute>();

但是没有成功的&#34; ViewData.ModelMetadata.ContainerType&#34;是空的。

有人有任何想法吗? (非常感谢提前)

1 个答案:

答案 0 :(得分:0)

谢谢@Brad。解决了这个问题:

@model dynamic

@foreach (var prop in ViewData.ModelMetadata.Properties)
{
    if (prop.TemplateHint == "HiddenInput")
    {
        @Html.Hidden(prop.PropertyName)
    }
    else
    {

             string attrclass = "";

             Type type = prop.ContainerType;

             if (type != null)
             {

                var attr = type.GetMember(prop.PropertyName)[0].GetCustomAttribute<ColumnAttribute>();

                if(attr!= null)
                {
                    attrclass = attr.Class;
                }


              }

            <div class="@attrclass">
                <div class="input-field">

                    @Html.Editor(prop.PropertyName)

                </div>

            </div>

}