cpoDesign
cpoDesign

Reputation: 9153

Using JavaScriptResult in my code

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:

  1. Code is rendered in controller and therefore I can interact with my data sources and more difficult calculation and logic.
  2. 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

Upvotes: 2

Views: 538

Answers (1)

Paweł Staniec
Paweł Staniec

Reputation: 3181

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.

Upvotes: 1

Related Questions