参数的ASP.NET MVC5自定义属性为空
本文关键字:自定义属性 MVC5 NET ASP 参数 | 更新日期: 2023-09-27 18:20:07
我有一个正在使用的自定义属性:
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);
}
}
然后,我想在视图中读取自定义属性的值,如下所示: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;