有两种方法可以访问它。
- 使用过滤器(或覆盖所有控制器派生自的基本控制器中的
OnActionExecuting 方法)将您需要的模型添加到 ViewBag/ViewData。
-
Use your own base
WebViewPage 公开模型,但您仍然需要填充它。因此,它可能需要访问您的 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 将可用于从该控制器派生的所有操作,无需额外工作。我建议将其设为属性,因为它可以让您更灵活地使用基类以及要将其应用于哪些控制器/动作。
方法二:提供自己的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>