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?


Comments

  1. Marcelo

    • 2015/1/31

    JavaScriptResult is considered an anti-pattern that Asp.net MVC introduced (complete separation of concerns), because it couples Controller and 

  2. Carson

    • 2019/3/10

    Return JavascriptResult Not Working. Share. was an example). Thanks. Browse other questions tagged javascript asp.net-mvc-3 controller or ask your own question.

  3. Harris

    • 2018/7/14

    JavaScript result sends JavaScript content to the response. Here we create one div element in the index.cshtml page. We write some text inside 

  4. Sinani

    • 2016/8/13

    Controller: public ActionResult Display () { var script = "$ ('#message').append ('Display');"; return JavaScript (script); } public ActionResult Checks () { string script = "var textboxvalue=$ ('#name').val ();"; script += "$ ('#message').append (textboxvalue);"; return JavaScript (script); } Output:

  5. Kannon

    • 2018/4/14

    hiHow to call javascript in controller on NetCoreits working like below in MVCusing HtmlBeginForm34Goo34 34Respond34 null FormMethodPost ltinput 

  6. Titus

    • 2020/3/1

    In ASP.NET MVC, you can JSONify anything. For example, Let’s modify the Home Controller as shown below public class HomeController : Controller { [HttpGet] public JsonResult Index() { return Json(new { Name = "John Smith", ID = 4, DateOfBirth = new DateTime(1999, 12, 31) }); } }

  7. Westley

    • 2019/5/11

    Now, run the application and navigates to Home/Index in the URL and you will get the following error. File Result, Content Result, Empty Result, JavaScript 

  8. Kylian

    • 2016/4/13

    the content type is set to text/javascript will cause most browsers to do a save as. you want to return html with inline script. return Content ("<script>alert ('hello world')</script>'); of course this is probably not what you want as the page will be replaced with the alert. note: the current version of jquery ajax will detect the script

  9. Sutton

    • 2018/3/28

    JavaScriptResult Class. Definition. Namespace: System.Web.Mvc. Assembly: System.Web.Mvc.dll. Package: Microsoft.AspNet.Mvc v5.2.6. Important.

  10. Remi

    • 2021/1/26

    Now let's create a link to call the javaScriptResult method of the Home controller. Here we use ajaxhelper to create a link. Ajaxhelper methods are called using "Ajax" property of the view. Using Ajaxhelper we can "submit a form" and "invoke an action method". So here we use Ajaxhelper to invoke the javascriptresult method using Ajax.ActionLink.

  11. Ricky

    • 2015/8/28

    Can somebody provide a working example of JavaScriptResult in asp.net mvc. I understand that it returns javascript which is then executed on the client side 

  12. Fox

    • 2016/1/30

    Here we will learn action results in asp.net mvc with examples and different action results available in asp.net mvc with examples. Asp.Net MVC Action Results. An ActionResult in asp.net mvc is an Abstract class, and ActionResult is the return type of controller method. Each ActionResult returns a different type of result. If we want to display an image in Webforms, we need to create Imagehandler for it, but in Asp.net MVC we can use FileResult that is already a built-in method.

  13. Lefebvre

    • 2019/5/24

    In this example I want to create a simple HTML including the base info for a user profile (Firstname, Lastname and website). The HTML Looks like 

  14. Jordy

    • 2020/9/21

    Currently ASP.NET MVC 6 doesn't support JavaScriptResult like in MVC 5. Working example for JavaScriptResult in asp.net mvc. 0. AJAX post JavaScript window.location.

  15. Kairo

    • 2018/7/2

    public JavaScriptResult OutputJavaScriptAlert() { string a = "alert('this is alert')"; return JavaScript(a); }. This action method returns JavaScript 

Comments are closed.

Recent Posts