ASP.NET MVC,在 Ajax 请求之间维护模型状态
问题: 在第一个完整页面请求中,我的控制器调用 applicationServices 层(我的业务层的 Web 服务代理),以便填充存储在我自己的控制器基类属性中的当前服务的集合。然后将其显示在视图中。 该控制器上下文中的所有内容都可以访问此“服务集合”。现在,当我通过 AJAX 调用进一步调用相同的操作方法时,我显然点击了该控制器的不同实例,这意味着我的服务集合是空的。
那么除了再次重新获取整个集合之外,我应该在哪里存储这个集合以便它在ajax请求之间得到持久化?我应该将其保留为单独的 DomainModel 对象、Session 对象吗?...因为 ViewData 不适合我。请原谅我对 MVC 的无知 :)
任何帮助将不胜感激 :)
problem:
On first full page request, my controller invokes an applicationServices Layer (Web Service Proxy to my business tier) in order to populate a collection of current services that is stored in my own controller base class property. This is then to be displayed within a view.
Everything within the context of that controller has access to this "Services Collection". Now when i make further calls to the same action method via an AJAX Call, i obviously hitt a different instance of that controller meaning my services collection is empty.
So other than re-getting the whole collection again, where would i store this collection so it gets persisted between ajax requests? Should i persist it as a seperate DomainModel Object, Session object?....as ViewData is not working for me obv. Excuse my MVC ignorance :)
Any help would be greatly appreciated :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Web 本质上是无状态的,MVC 可以帮助您深入了解,也就是说,MVC 不会尝试创建一些无状态的东西,这主要是旧 ASP 的路径:每个请求都是它自己的请求并且它不应该知道过去执行过的任何其他请求。
我觉得沿着这条路线走是最简单的,因为它往往保持干净、快速,并帮助您遵守关注点分离等最佳实践。
AJAX 更进一步:AJAX 的思想是可以实现简单的“删除”操作,即您只需要在持久层上授权并执行一个非常小的查询。就是这样。您甚至不需要将修改后的页面传递回用户。通过 JSON 的简单机器可读成功/错误指示就足够了。
如果您开始为小型 AJAX 请求提供大量服务,那么您确实会失去大部分好处。
我还建议您不要在基本控制器中存储大量服务。对于大多数请求,您可能只需要其中的一小部分。最佳做法是仅检索您绝对需要的服务。
The web is essentially stateless and MVC helps you to go down to the metal, that is, MVC does not try to make something stateful that isn't, which is mostly the path of ye olde ASP: Each request is a request of it's own and it shouldn't know anything about any other request that has been performed in the past.
I feel it is easiest to go down exactly that route, because it it tends to stay clean, fast and helps you in adhering to best practices such as separation of concerns.
AJAX takes this a step further: The idea of AJAX is that a simple 'delete' operation can be implemented as such, i.e. you only need to authorize and perform one very small query on the persistence layer. That's it. You don't even need to pass a modified page back to the user. A simple machine-readable success/error indication via JSON is sufficient.
If you start to pull lots of services around for small AJAX requests, you really lose most of what it's good for.
I'd also suggest you don't store a bunch of services in a base controller. Chances are that for most requests, you will only need a small subset of these. It's best practices to retrieve only those service you absolutely positively need.