有两种方法可以使其可访问。
- 使用过滤器(或覆盖
OnActionExecuting
您的控制器都派生自的基本控制器中的方法)添加您需要的模型ViewBag
/ViewData
.
-
使用自己的基地WebViewPage https://stackoverflow.com/questions/14358410/changing-base-view-type-on-mvc4公开模型,但您仍然需要填充它。因此,它可能需要访问您的 API,并且正确完成,可能需要一些依赖项注入。
方法一:OnActionExecuting
从基本控制器覆盖
public abstract MyBaseController : Controller
{
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (User != null && User.Identity.IsAuthenticated) // check if user is logged in if you need to
{
ViewBag.LoginModel = /* add data here */;
}
}
}
然后将其用作基类(或继承中更靠前的位置):
public MyController : MyBaseController
{
//etc.
}
或者使用过滤器
PopulateLoginModelAttribute : ActionFilterAttribute, IActionFilter
{
void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.HttpContext.User != null && filterContext.HttpContext.User.Identity.IsAuthenticated)
{
filterContext.Controller.ViewBag.LoginModel = /* add data here */;
}
this.OnActionExecuting(filterContext);
}
}
然后装饰控制器类、操作方法或添加为全局过滤器。
[PopulateLoginModel] // will be applied to all actions in this controller
public class MyController : Controller // note you can use the normal base type, or whatever you need
{
public ActionResult MyView()
{
return View(new CartModel());
}
}
然后使用您放置在中的模型ViewBag
在引用的部分、布局等中,但继续使用Model
对于操作的视图。
访问ViewBag
通常在您的视图中(也可以通过布局访问,我在 LoginModel 类型上编写了一个属性值来说明):
<span>@ViewBag.LoginModel.Name</span> <!-- available because of the filter !-->
Number of items in your cart: @Model.Items.Count <!-- the model provided by the action method !-->
ViewBag.LoginModel
将可用于从此控制器派生的所有操作,无需额外工作。我建议将其设为一个属性,因为它将为您提供基类以及要将其应用到的控制器/操作的更大灵活性。
方法2:提供自己的WebViewPage基类
您不太可能想要使用自己的 WebPageView 基类。如果您想添加成员来协助处理数据或视图的任何内容,那么这非常适合。但这不是添加或以其他方式操作视图数据或模型的正确位置,尽管这是可能的。
创建视图基类
public abstract class MyWebViewPage<T> : WebViewPage<T>
{
protected LoginModel GetLoginModel()
{
// you could resolve some dependency here if you need to
return /* add data here */
}
}
然后在视图、局部视图和布局中使用成员
确保视图文件夹中的 web.config 已正确更新。
<span>@GetLoginModel().Name</span>