One way would be to use an HTML helper:
public static class HtmlExtensions
{
public static bool IsAdministrator(this HtmlHelper htmlHelper)
{
var controller = htmlHelper.ViewContext.Controller as BaseController;
if (controller == null)
{
throw new Exception("The controller used to render this view doesn't inherit from BaseContller");
}
return controller.IsAdministrator;
}
}
And in your view:
<% if (Html.IsAdministrator()) { %>
<% } %>
UPDATE:
@jfar's comment about the MVC paradigm is correct. Here's what you could do in practice to implement it. You could define a base view model class that all your view models derive from:
public class BaseViewModel
{
public bool IsAdministrator { get; set; }
}
and then write a custom action filter attribute which will execute after the action and set the property:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class AdministratorInjectorAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
base.OnActionExecuted(filterContext);
var result = filterContext.Result as ViewResultBase;
if (result != null)
{
// the action returned a strongly typed view and passed a model
var model = result.ViewData.Model as BaseViewModel;
if (model != null)
{
// the model derived from BaseViewModel
var controller = filterContext.Controller as BaseController;
if (controller != null)
{
// The controller that executed this action derived
// from BaseController and posses the IsAdministrator property
// which is used to set the view model property
model.IsAdministrator = controller.IsAdministrator;
}
}
}
}
}
And the last part is to decorate the BaseController with this attribute:
[AdministratorInjector]
public abstract class BaseController : Controller
{
public bool IsAdministrator { get; set; }
}
Finally if your view is strongly typed to a model that derives from BaseViewModel
you could directly use the IsAdministrator
property:
<% if (Model.IsAdministrator) { %>
<% } %>
Probably a bit more code than the HTML helper, but your consciousness about respecting MVC paradigm will be clear.