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="https://stackoverflow.com/JS/Global"></script>

Now I can get the values in any Javascript file:

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

Leave a Comment