繁体   English   中英

参数上的ASP.NET MVC5自定义属性为空

[英]ASP.NET MVC5 Custom Attribute on Parameter is empty

我有一个自定义属性,正在使用:

public class Plus.ViewModels {

    [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Class | AttributeTargets.Constructor, AllowMultiple = true)]
    public class ExcludeFilterAttribute : Attribute
    {
        public string FilterToExclude { get; private set; }
        public ExcludeFilterAttribute(string filterToExclude)
        {
            this.FilterToExclude = filterToExclude;
        }
    }
}

我在控制器的操作参数上使用它,如下所示:

public class MyController 
{
     public ActionResult AggregationClientBase([ExcludeFilter("Categories")] AggregationFiltersViewModel filters)
     {
         return View(filters);
     }
}

然后,我想像这样在View中读取自定义属性的值:Type type = Model.GetType();

@model AggregationFiltersViewModel
@{
    Type type = Model.GetType();
    ExcludeFilterAttribute[] AttributeArray = (ExcludeFilterAttribute[])type.GetCustomAttributes(typeof(ExcludeFilterAttribute), false);

    ExcludeFilterAttribute fa = AttributeArray[0];   
}

然后

@if (fa.FilterToExclude != "Categories")           
{
    <th>Category:</th>
    <td>@Html.DropDownListFor(m => m.SelectedCategoryId, Model.Categories)</td>
}

但是,自定义属性的数组为空,因此出现以下错误:

Index was outside the bounds of the array. System.IndexOutOfRangeException: Index was outside the bounds of the array.

如何获取自定义属性的值? 我知道我只能传递值模型变量,但是当我要排除的集合很大时,使用自定义属性会更容易。

您正在尝试从模型获取属性,但它是在控制器的AggregationClientBase方法内部定义的。

所以:

var controllerType = typeof(YourController);
var method = controllerType.GetMethod("AggregationClientBase");
var parameter = method.GetParameters().First(p => p.Name == "filters");

var fa = parameter.GetCustomAttributes(typeof(ExcludeFilterAttribute), false)
                  .First() as ExcludeFilterAttribute;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM