在我的代码中使用 JavaScriptResult
我一直在想我是否应该使用 JavaScriptResult? 我读过几篇关于此的文章,人们的观点相互矛盾。
我可以看到好处:
- 代码在控制器中呈现,因此我可以与我的数据源以及更困难的计算和逻辑进行交互。
- 但是使用渲染的 jasonresult 基于页面渲染的 JS 似乎是更好的选择。
不确定编程模式:
控制器中的 JavaScript 渲染如何适合模型视图控制器
I have been wondering whether I should be using JavaScriptResult?
I have read couple articles about this and people have contradicting opinions.
I can see benefit:
- Code is rendered in controller and therefore I can interact with my data sources and more difficult calculation and logic.
- But JS rendered based on page using rendered jasonresult seem to be better choice.
Not sure about programming pattern:
How does JavaScript rendering in controller fits with Model View Controller
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
MVC 是一种关注点分离的设计模式。我经常听说 JavaScriptResult 是应该避免的,因为它打破了这一原则。在我看来,您应该记住这一点,MVC 为您提供了强大的工具,但这取决于您,您将如何使用它们。 JavaScript XHR / Ajax 不仅可以提供 GUI 渲染,但应谨慎使用。好吧,事实是,即使是最简单的方法也可能会被误用,但这并不意味着我们不应该使用它们:)
当然,在页面上使用 JavaScript 并使用 JSON 来提供它是非常好的,并且在大多数情况下都是可取的。情况下就足够了。但有时,您需要选择是 100% 遵守 MVC 模式还是 DRY 原则/其他良好实践。我认为最好在特定情况下做你认为有意义的事情。
让我们采用 WebGrid 帮助程序的 GetContainerUpdateScript 方法 http://msdn.microsoft.com/en-us/library/system.web.helpers.webgrid.getcontainerupdatescript(v=vs.99).aspx 它提供 jquery oneliner 来更新您的网络网格数据。在本例中,所有内容都在视图中,但类似的代码可能是控制器的一部分 - 假设一个脚本根据某些唯一标识符(例如类似 sessionID)发出一堆 POST 请求。
在我看来,还有比在 View 和 Controller 之间踩一条细红线(有时稍微跨越它)来避免其他问题、使代码更干净、更可重用和可维护更糟糕的事情。
MVC is the design pattern which is all about separation of concern. I often hear that JavaScriptResult is something to avoid as it breaks that princple. In my opinion you should keep that in mind that MVC gives you powerful tools but it's up to you, what will you do with them. JavaScript XHR / Ajax can deliver more than only GUI renderring, but should be used with consideration. Well, fact is one can missuse even the simpliest methods, but that doesn't mean we shouldn't use them :)
Of course, using JavaScript on your page, and feeding it with JSON is perfectly fine and prefferable, in most of the cases it's sufficient. Sometimes though, you will need to choose wether you want to be 100% compliant with MVC pattern or DRY principle / other good practices. I think it's best to do what you think makes sense in a particular situation.
Let's take WebGrid helper's GetContainerUpdateScript method http://msdn.microsoft.com/en-us/library/system.web.helpers.webgrid.getcontainerupdatescript(v=vs.99).aspx it delivers jquery oneliner to update your webgrid data. In this case it's all in the View, but similar code could be a part of the controller - let's say a script that makes bunch of POST requests based on some unique identifier (sessionID-like for example).
In my opinion there are worse things than stepping on a thin red line between View and Controller (and sometimes crossing it slightly) to avoid other problems, make your code cleaner, more reusable and maintainable.