Reputation: 4489
If i set an Attribute on an action in a controller that inherits BaseController, is it possible to get that value in some BaseController function?
public class BaseController : Controller
{
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{ .... want to get the value of DoNotLockPage attribute here? }
public class CompanyAccountController : BaseController
{
[DoNotLockPage(true)]
public ActionResult ContactList()
{...
Upvotes: 2
Views: 3481
Reputation: 4489
Took a different route. I could have simply created a variable in the basecontroller and set it to true in any action. But i wanted to use an Attribute, just easier to understand code. Basically in the basecontroller i had code that would lock the page under certain conditions, view only. But being in the base class this would effect every page, there were a couple actions i needed always to be set to edit.
I added a property to the basecontroller. And in the OnActionExecuting of the Attribute, i'm able to get the current controller and set it the property to true.
This way i was able to get my attribute setting in my override of ViewResult.
My Attribute
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public sealed class DoNotLockPageAttribute : ActionFilterAttribute
{
private readonly bool _doNotLockPage = true;
public DoNotLockPageAttribute(bool doNotLockPage)
{
_doNotLockPage = doNotLockPage;
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var c = ((BaseController)filterContext.Controller).DoNotLockPage = _doNotLockPage;
}
}
My base controller
public class BaseController : Controller
{
public bool DoNotLockPage { get; set; } //used in the DoNotLock Attribute
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{ ...... }
protected override ViewResult View(string viewName, string masterName, object model)
{
var m = model;
if (model is BaseViewModel)
{
if (!this.DoNotLockPage)
{
m = ((BaseViewModel)model).ViewMode = WebEnums.ViewMode.View;
}
....
return base.View(viewName, masterName, model);
}
}
}
Upvotes: 2