我正在使用MVC 2.
我有一个每个Controller使用的BaseController类。在此基本控制器类中,有一个名为IsAdministrator的属性。我需要在我的视图的HTML部分中使用此方法。我该怎么做?
编辑:
我的BaseController中的属性定义如下:
public bool IsAdministratorUser
{
get { return ... }
}
答案 0 :(得分:14)
一种方法是使用HTML帮助程序:
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;
}
}
在你看来:
<% if (Html.IsAdministrator()) { %>
<% } %>
更新:
@jfar关于MVC范式的评论是正确的。以下是您在实践中可以执行的操作。您可以定义所有视图模型派生自的基本视图模型类:
public class BaseViewModel
{
public bool IsAdministrator { get; set; }
}
然后编写一个自定义操作过滤器属性,该属性将在操作后执行并设置属性:
[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;
}
}
}
}
}
最后一部分是用这个属性装饰BaseController:
[AdministratorInjector]
public abstract class BaseController : Controller
{
public bool IsAdministrator { get; set; }
}
最后,如果您的视图强烈输入到源自BaseViewModel
的模型,则可以直接使用IsAdministrator
属性:
<% if (Model.IsAdministrator) { %>
<% } %>
可能比HTML助手多一些代码,但是你对尊重MVC范式的意识将会很明确。