Working example for JavaScriptResult in asp.net mvc

Note: This answer was written in 2011 and looking at it nowadays, it's more of a hack. It's better to load values through AJAX request that hits a JSON endpoint API.

Here's a practical case: I have a GlobalSettings static C# class that contains static Properties of values that are used through the whole system in the ASP.NET MVC backend side of things.

Some of those values need to be shared with JS code. So I created an Action that returns JavaScriptResult which basically pumps out those values into global JS variables.

Note: Change the output cache period to suit your needs

[OutputCache(Duration = 999999)]
public virtual JavaScriptResult Global()
{
        var script = $@"
            MaxNotificaitonsToShow = {GlobalSettings.MaxNotificaitonsToShow};
            ItemsPerPage = {GlobalSettings.ItemsPerPage};
        ";
    return JavaScript(script);
}

And then I load the response of this action as a JS file inside all pages through the HTML footer:

<script type="text/javascript" src="/JS/Global"></script>

Now I can get the values in any Javascript file:

if(ItemsPerPage == 25)
{
   alert('it works!');
}

Avoid if possible

JavaScriptResult is considered an anti-pattern that Asp.net MVC introduced (complete separation of concerns), because it couples Controller and View back together to make them dependable on eachother. In a pure Asp.net MVC application where the UI is build on Asp.net MVC and server side serves this client implementation only it is thus advised to avoid this functionality.

It may be useful in other scenarios. I can remember I've been reading something related to Ruby on Rails clients.

Anyway.

An example that does make sense

An actual example would be to return javascript code to an Ajax request that would simply provide some functionality that will get executed immediately upon response without any data manipulation.

Where could you possibly benefit from it? Well think of an application that has huge amounts of various client classes used thoughout the application. But certain pages use only a small fraction (or even a dynamic fracion) of them. In this case you would have two possibilities:

  1. Load the whole client class tree upfront - either in a huge single file or fragmented in separate files (this would be ok if views would use a small sub set of up-front known classes, because otherwise this would result in lots of server requests)
  2. Load classes on demand when they are needed - or maybe even execute certain class functions on demand when and if they are needed.

In this particular case, the second scenario would be much better and much more efficient in terms of network traffic, client memory resources and processor load.


Check out my reply in this post;

MVC how to return instruction to run javascipt method?

That will return a partial view to the page. If you want to itterate through a json object then return a json object from your controller and use something like the following;

var obj = eval('(' + msg + ')');

msg above is the returned object from your controller;

then,

$.each(obj.Objects, function() { do something with object });

"Objects" above is a property within the returned json object.

So in c#

public class JsonObject()
{
  List<MyObjectList> Objects{get;set;}
}

Return the above object to the view.

Does this make sense or would you like a working sample?