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

时间:2014-09-01 06:22:53

标签: c# asp.net razor asp.net-mvc-5 custom-attributes

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

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

我正在将参数用于Controller的操作,如下所示:

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.

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

1 个答案:

答案 0 :(得分:1)

您正在尝试从模型获取属性,但它是在控制器中的方法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;