In this tutorial, we're gonna discuss about how to return JavaScript Content from controller action method. I have created a demonstration here, let's follow it step by step.

Step 1

Create a controller action method that returns a view:

public ActionResult OutputJavaScript()
  {
      return View();
  }

View for above action method:

@{
    ViewBag.Title = "OutputJavaScript";
}

<h2>OutputJavaScript</h2>

Try clicking on the link below <br />

@Html.ActionLink("Test JavaScript", "OutputJavaScriptAlert)

Step 2

The view appears in the browser like below:

Notice the 2nd parameter of the ActionLink method, this is the action method name of the controller. When the link “Test JavaScript” is clicked, it calls the OutputJavaScriptAlert action method of the controller.

Step 3

Controller code:

public JavaScriptResult OutputJavaScriptAlert()
  {
      string a = "alert('this is alert')";
      return JavaScript(a);
  }


This action method returns JavaScript content that we get it in the new window or to download as displayed in the above picture (depending on the browser).

In general, these methods are used in the Ajax methods to return partial content.

HostForLIFE.eu ASP.NET MVC 6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.