扩展现有 MVC 站点以将每个操作的新数据传递到 ViewData
我们有一个基于 Asp.Net MVC2 构建的白标平台。目前该站点有 6 个控制器,以及所有核心视图等,使其能够开箱即用。到目前为止,我们已经用它建立了 5 个站点,一切都很棒。
然而,现在我有一个要求,这意味着我需要能够从任何操作将一条新数据(在 ViewData 字典中就可以)传递到所有视图。该数据从查询字符串中播种,然后从 cookie 中播种。
这样做的主要原因之一是能够根据此数据的值向网站的主页添加额外的图像。我当然可以非常肮脏地将反序列化代码放在母版页中;但我宁愿找到一种方法来确保将其添加到每个请求的 ViewData 中不涉及控制器继承和操作方法重写(!)。
任何想法都非常感谢!
We have a white-labelled platform built on Asp.Net MVC2. At present the site has 6 controllers, as well as all the core views etc that can enable it to work straight out of the box. So far we've built 5 sites from it and it's all been great.
Now, however, I have a requirement that means I need to be able to pass a new piece of data (in the ViewData dictionary will be fine) to all views from any action. This data is seeded from query string and then from a cookie.
One of the primary reasons for this is to be able to add an extra image to the site's master page depending on this data's value. I could of course be really dirty and place the deserialization code in the master page; but I'd rather find a way to ensure that it gets added to the ViewData for every request that doesn't involve controller inheritance and action method overriding(!).
Any ideas greatly greatly appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以编写自定义操作过滤器属性,并将此属性应用于基本控制器或需要注入此信息的所有操作:
然后使用此属性装饰您的基本控制器:
在 ASP.NET MVC 3 中,有一个 全局操作过滤器 这样你甚至不需要有一个基本控制器或用这个过滤器装饰你的所有动作。有一个解决方法可以让您在 ASP.NET MVC 2 中实现相同的效果。现在,您的所有视图都在视图数据中获得了这个附加属性。
话虽这么说,前面的方法是一个丑陋的解决方法,我不推荐(ViewData 很丑陋)。您可以查看 Html.Action 和 Html.RenderAction 帮手。其外观如下:
然后有一些强类型部分,其中将包含所需的 HTML (
~/Views/MySpecial/Index.ascx
),最后将其包含在您的母版页中:You could write a custom action filter attribute and apply this attribute to a base controller or all actions that need to have this information injected:
And then decorate your base controller with this attribute:
In ASP.NET MVC 3 there's a notion of global action filters so that you don't even need to have a base controller or decorate all your actions with this filter. There's a workaround allowing you to achieve the same in ASP.NET MVC 2. Now all your views get this additional property in the view data.
This being said, the previous is an ugly workaround and not something I would recommend (ViewData is ugly). You may take a look at Html.Action and Html.RenderAction helpers. Here's how this might look:
Then have some strongly typed partial which will contain the required HTML (
~/Views/MySpecial/Index.ascx
) and finally include this in your master page:重写基本控制器中的
OnResultExecuting
并将所需数据添加到ViewData
属性中。Override
OnResultExecuting
in your base controller and add required data to theViewData
property..