Reputation: 899
I have a custom attribute I am using:
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;
}
}
}
I am using it on the parameter to a Controller's action like so:
public class MyController
{
public ActionResult AggregationClientBase([ExcludeFilter("Categories")] AggregationFiltersViewModel filters)
{
return View(filters);
}
}
I then want to read the value of the custom attribute in the View like this: Type type = Model.GetType();
@model AggregationFiltersViewModel
@{
Type type = Model.GetType();
ExcludeFilterAttribute[] AttributeArray = (ExcludeFilterAttribute[])type.GetCustomAttributes(typeof(ExcludeFilterAttribute), false);
ExcludeFilterAttribute fa = AttributeArray[0];
}
Then
@if (fa.FilterToExclude != "Categories")
{
<th>Category:</th>
<td>@Html.DropDownListFor(m => m.SelectedCategoryId, Model.Categories)</td>
}
However, the array of custom attributes is empty, so I get the following error:
Index was outside the bounds of the array. System.IndexOutOfRangeException: Index was outside the bounds of the array.
How can I get the value of the custom attribute? I know I can just pass values model variables, but using a custom attribute makes is easier when I have a large collection to exclude.
Upvotes: 0
Views: 495
Reputation:
You are trying to get attribute from model, but it is defined inside method AggregationClientBase
in your controller.
So:
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;
Upvotes: 1