我有以下场景,可能需要将数据存储在控制器成员变量中,以便在操作之间共享数据。
我有一个搜索表单和一个按钮 - 单击时,会根据搜索表单参数返回一个充满数据的表格。一个动作——一切都好又干净。
现在要求我放置一个 Excel 按钮,以便用户可以下载 Excel 格式的表格。我不想再次运行数据库查询,因为数据已经存在,但由于我使用服务器端 Excel 组件,我需要服务器上可用的数据才能将其推送到 Excel 中。
我最初的想法是在控制器中添加一个额外的变量来存储数据。但我从未见过在 ASP.NET MVC 中这样做。这是公认的模式吗?我的理解是每个动作都是孤立的。
I have the following scenario that may warrant storing data in a conroller member variable in order to share it between actions.
I have a search form and a button - when clicked, a table full of data returns according to the search form parameters. One action - all good and clean.
I am now asked to put an excel button so that the user can download the table in excel format. I don't want to run the db query again, since the data is already there, but since I am using a server side Excel component, I need the data to be available on the server in order to shove it into Excel.
My initial idea was to have an extra variable in my controller where the data can be stored. But I have never seen this being done in asp.net MVC. Is this an accepted pattern? My understanding was that each action is sort of isolated.
发布评论
评论(3)
MVC 模式鼓励无状态。这意味着如果您想在操作之间保留数据,则需要从客户端发布数据(服务器不应维护与特定会话相关的任何状态)。 (所以是的,每个操作都应该是隔离的,并且不应该依赖于任何先前的操作,即它不应该依赖于先前请求的设置)
阅读 scott Gu 的博客,了解 MVC 的含义 http://weblogs.asp.net/scottgu/archive/2007/10/14/asp-net-mvc-framework.aspx
如果您在访问数据时遇到性能问题,我的建议是使用数据获取的服务器端缓存。理想情况下,这应该在应用程序的数据访问或查询层中实现,并且不应与特定会话紧密相关
The MVC pattern encourages statelessness. This means if you want to keep data between actions it needs to get posted from the client (the server shouldn't maintain any state relating to a specific session). (so yes each action should be isolated, and shouldn't be reliant on any previous action, ie it shouldn't rely on setup from a previous request)
Take a read of scott Gu's blog on what MVC means here http://weblogs.asp.net/scottgu/archive/2007/10/14/asp-net-mvc-framework.aspx
If you are having performance problems accessing data my recommendation is to use serverside caching of your data fetch. This should ideally be implemented in your data access or query layer in your application and shouldnt be strongly tied to a specific session
每次请求后控制器都会被丢弃。每次你都会得到一个新的。如果要存储数据,最简单的方法是将其置于会话状态。
The controller is thrown away after each request. You get a new one everytime. If you want to store the data, the easiest would be to put it into session state.
我建议使用 TempData,例如这里描述的 http://rachelappel.com/when-to-use-viewbag-viewdata-or-tempdata-in-asp.net-mvc-3-applications
更新:返回文件按照此处完成 返回文件以在 ASP.NET MVC 中查看/下载
通常的做法是使用单独的控制器来返回文件。
I would suggest to use TempData, for example it's described here http://rachelappel.com/when-to-use-viewbag-viewdata-or-tempdata-in-asp.net-mvc-3-applications
Update: return file as done here Returning a file to View/Download in ASP.NET MVC
It's a normal practice to have a separate controller to return the file.