Returning JavaScript from action method in ASP.NET MVC

How to output JavaScript content from controller action method?


To demonstrate how to return JavaScript content from the controller, we have created a demonstration here. Let’s follow that step by step.
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)
And 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.
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.

No comments:

Post a Comment

How to register multiple implementations of the same interface in Asp.Net Core?

 Problem: I have services that are derived from the same interface. public interface IService { } public class ServiceA : IService { ...