我应该在哪里编辑 BaseModelView(在 BaseController 中)?
我创建了一个所有控制器都继承自的基本控制器。目前,此控制器将一些数据(我在大多数视图中使用)填充到 ViewData-Container 中,如下所示:
protected override void Initialize(System.Web.Routing.RequestContext rc)
{
base.Initialize(rc);
ViewData["cms_configuration"] = new CmsConfiguration();
// etc.
}
我不喜欢需要从视图中的 ViewData 读取(和转换)的事实。我想引入一个 BaseViewModel,所有 ViewModel 都将从它继承,定义属性而不是使用 ViewData。但是如何或在哪里可以在 BaseController 中填充 BaseViewModel?有某种钩子吗?或者我只需要在 BaseController 中定义一个函数,然后在 Child-Controller 中调用它?
例如(儿童控制器:
//{...}
base.PopulateBaseView(MyView);
return View(MyView);
谢谢您的任何提示。 SL3DG3
I have created a Base-Controller from which all the controllers inherit. Currently this controller fills some data (which I use in most views) into the ViewData
-Container like this:
protected override void Initialize(System.Web.Routing.RequestContext rc)
{
base.Initialize(rc);
ViewData["cms_configuration"] = new CmsConfiguration();
// etc.
}
I don't like the fact that I need to read (and cast) from ViewData within the views. I'd like to introduce a BaseViewModel from which all ViewModels will inherit from, defining the properties instead of using ViewData. But how or where can I populate the BaseViewModel within the BaseController? Is there some kind of hook? Or do I simply need to define a function in BaseController, which I call in the Child-Controller?
E.g. (Child-Controller:
//{...}
base.PopulateBaseView(MyView);
return View(MyView);
Thx for any tipps.
sl3dg3
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以选择使用 ActionFilters 来做这样的事情:
查看这篇文章:
http ://www.asp.net/mvc/tutorials/understanding-action-filters-cs
它很好地解释了 ActionFilters。这样您就可以将不同的填充逻辑分离到不同的过滤器中,并根据需要打开和关闭它们。
You could optionally use ActionFilters to do stuff like this:
Check out this article:
http://www.asp.net/mvc/tutorials/understanding-action-filters-cs
It explains ActionFilters nicely. That way you can separate different populate-logic into different filters, and turn them on and off as you please.