Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at imagehelp@codebetter.com
Beware of ASP.NET MVC JavaScriptResult

 

One of the immense advantages that ASP.NET MVC has over classic ASP.NET is the clean separation of concerns between the presentation and controller logic.  Unfortunately, while the MVC RC has brought with it many improvements, it has also taken a step towards breaking down the clean separation of concerns with the introduction of the JavaScriptResult ActionResult.  Per the release notes, "the JavaScriptResult class is used to execute JavaScript code that is created on the server and sent to the client."  The release notes even go as far to include the following code example:

public ActionResult DoSomething() { script s = "$('#some-div').html('Updated!');"; return JavaScript(s); }

While I can surmise that there is more than one useful scenario for the inclusion of JavaScriptResult, the above example should be seen as an anti-pattern of its use.  This example is introducing a very fragile dependency into the controller on the view itself.  In classic ASP.NET, the code-behind page was able to have strongly typed access to elements in the view.  In the above scenario, a similar dependency is introduced into the controller, but now it's not even strongly typed.

Like extension methods and lambda expressions, JavaScriptResult puts more power into the hands of the developer, but also assists in shooting yourself in the foot if used improperly.  So like any powerful .NET tool, have a good reason to use it, keep an eye on proper separation of concerns, and always keep testability and maintainability strongly in your design.

Billy McCafferty


Posted 02-07-2009 8:38 PM by Billy McCafferty
Filed under: ,

[Advertisement]

Comments

brad wrote re: Beware of ASP.NET MVC JavaScriptResult
on 02-08-2009 2:24 AM

i cant honestly think of an example of needing that...

Beware of ASP.NET MVC JavaScriptResult - Billy McCafferty wrote Beware of ASP.NET MVC JavaScriptResult - Billy McCafferty
on 02-08-2009 6:01 AM

Pingback from  Beware of ASP.NET MVC JavaScriptResult - Billy McCafferty

JohnR wrote re: Beware of ASP.NET MVC JavaScriptResult
on 02-08-2009 8:35 AM

Can you elaborate a bit on how to best tackle this kind of scenario with ASP.Net MVC? Where does this kind of code belong?

DotNetShoutout wrote Beware of ASP.NET MVC JavaScriptResult - Billy McCafferty
on 02-08-2009 9:11 AM

Thank you for submitting this cool story - Trackback from DotNetShoutout

Billy McCafferty wrote re: Beware of ASP.NET MVC JavaScriptResult
on 02-08-2009 10:15 AM

JohnR,

If you're asking what context this is in, the JavaScriptResult is intended to be used within your MVC controller.  Let me know if that does not answer your question.

PaulBlamire wrote re: Beware of ASP.NET MVC JavaScriptResult
on 02-08-2009 4:27 PM

Hi,

I may be mistaken but I think the idea is to support RJS style results as per ruby on rails.

In RJS you have a page helper class that actually produces the javascript, with methods to show/hide.flash etc.

Ultimately you are right in that a degree of coupling is produced, e.g. if you write code like Page.Flash('div1') your controller is at the very least aware of your html ids.

However for simple scenarios it can be worth the tradeoff, as long as you understand you are making a tradeoff that is :-)

Kind regards,

Paul

Dew Drop - Weekend Edition - February 7-8, 2009 | Alvin Ashcraft's Morning Dew wrote Dew Drop - Weekend Edition - February 7-8, 2009 | Alvin Ashcraft's Morning Dew
on 02-08-2009 9:18 PM

Pingback from  Dew Drop - Weekend Edition - February 7-8, 2009 | Alvin Ashcraft's Morning Dew

ASP.NET MVC Archived Blog Posts, Page 1 wrote ASP.NET MVC Archived Blog Posts, Page 1
on 02-08-2009 11:21 PM

Pingback from  ASP.NET MVC Archived Blog Posts, Page 1

sv wrote re: Beware of ASP.NET MVC JavaScriptResult
on 02-12-2009 10:13 AM

When will you release sharp-architecture for ASP.NET MVC RC?

Billy McCafferty wrote re: Beware of ASP.NET MVC JavaScriptResult
on 02-12-2009 11:00 AM

The trunk is currently compatible with RC...but there's an important change I'm committing very shortly (within an hour or so of your comment) before putting together an RC release.  Thanks for the interest!

DotNetKicks.com wrote Beware of ASP.NET MVC JavaScriptResult
on 02-12-2009 5:13 PM

You've been kicked (a good thing) - Trackback from DotNetKicks.com

Chris wrote re: Beware of ASP.NET MVC JavaScriptResult
on 08-21-2009 11:20 AM

Does this actually update the contents of 'some-div'?  All I am seeing is a black page with the text "$('#some-div').htm('Updated!');"

Billy wrote re: Beware of ASP.NET MVC JavaScriptResult
on 08-21-2009 3:15 PM

It simply returns JavaScript to be executed on the client side.  The point is that, IMO, JavaScript shouldn't be put together and returned to the view from the controller since it is a presentation concer.

Erx wrote re: Beware of ASP.NET MVC JavaScriptResult
on 02-24-2010 7:14 PM

Bill, could you tell us how best to tackle the approach and substitute the function code you presented with a more maintainable/legitimate example where seperation of concerns are withheld?

Geoff wrote re: Beware of ASP.NET MVC JavaScriptResult
on 05-25-2011 1:45 PM

Having this ActionResult is very useful if you happen to be building an action method that is the endpoint for a JSONP call.

For example:

[HttpGet]

public ActionResult JSONP(string callback)

{

 object data = new { FirstName = "Jon", LastName="Doe" };

 JavaScriptSerializer serializer = new JavaScriptSerializer();

 JavaScriptResult result = new JavaScriptResult();

 result.Script = callback + "(" + serializer.Serialize(data) + ");";

 return result;

}

CarlWorx wrote re: Beware of ASP.NET MVC JavaScriptResult
on 09-23-2011 5:04 PM

Well there are occasions that this is needed, in my case I had to use it with my third party html editor - TinyMce. http://www.tinymce.com/#

TinyMCE object has an option to set its property external_image_list_url, see below:

tinyMCE.init({

       ...

       external_image_list_url : "myexternallist.js"

});

this is expecting a link to a physical javascript file. Since I have to retrieve my dynamic data at the server,

I had to build my js script on the fly and return the response as a javascript  file. See response header Content-Type below after returning a Javascript() result.

Server                               ASP.NET Development Server/10.0.0.0

Date                               Fri, 23 Sep 2011 20:45:50 GMT

X-AspNet-Version       4.0.30319

X-AspNetMvc-Version 3.0

Cache-Control                private

Content-Type                application/x-javascript; charset=utf-8

Content-Length                186

Connection                       Close

If I was the one who made tinyMCE, I would set the external_image_list_url to expect a list in JSON format. However I'm not the one who made tinyMCE and I don't have the luxury of time to create such a powerful tool myself, so I had to work around it and make use of  the Javascript result feature in MVC.

my two cents. :)

David wrote re: Beware of ASP.NET MVC JavaScriptResult
on 11-21-2011 2:19 PM

If you're wondering where this kind of response would be applicable, it might help to try Ruby on Rails. It would also give you insight into the future releases of ASP.NET's implementation of MVC because that's where Microsoft draws all of its inspiration for MVC.NET. Imitation is the highest form of flattery!

bookmarks wrote re: Beware of ASP.NET MVC JavaScriptResult
on 03-15-2013 1:19 AM

x7P5be Awesome article.Really thank you! Fantastic.

About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Subscribe
Google Reader or Homepage

del.icio.us CodeBetter.com Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl CodeBetter.com Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of Devlicio.us
Red-Gate Tools For SQL and .NET

NDepend

SlickEdit
 
SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
LiteAccounting.Com
DevExpress
Fixx
NHibernate Profiler
Unfuddle
Balsamiq Mockups
Scrumy
JetBrains - ReSharper
Umbraco
NServiceBus
RavenDb
Web Sequence Diagrams
Ducksboard<-- NEW Friend!

 



Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers

 

Community Server (Commercial Edition)