Divyang Desai
Divyang Desai

Reputation: 7864

How to return JavaScript from controller?

I'm working with the ASP.NET Core 2.2 project where I need to return JavaScript from the controller. However, I suspect that there is no direct way, hence, I followed this OS answer and changed my code as following:

public IActionResult MyAction()
{
    var sb = new StringBuilder();
    sb.Append("$(document).ready(function(){");
    sb.Append("alert('hi')");
    sb.Append("});");            
    return new JavaScriptResult(sb.ToString());
}

public class JavaScriptResult : ContentResult
{
    public JavaScriptResult(string script)
    {
        this.Content = script;
        this.ContentType = "application/javascript";
    }
}

Though it's just writing plain text instead. Is there way around?

Upvotes: 9

Views: 10741

Answers (2)

Nur.B
Nur.B

Reputation: 397

You need to add a second parameter Content-type and return "Content" instead of JavaScriptResult:

`public IActionResult MyAction()
{
  var sb = new StringBuilder();
  sb.Append("$(document).ready(function(){");
  sb.Append("alert('hi')");
  sb.Append("});");            
  return Content(sb.ToString(), "text/html");
}`

Upvotes: 2

Nan Yu
Nan Yu

Reputation: 27578

You can use ajax to load the javascript , in your page :

<script>
    $(function () {
            $.getScript("/Controller/Action");
    });

</script>

Your serve side :

public IActionResult DoSomething()
{
    return new  JavaScriptResult("alert('Hello world!');");
}

public class JavaScriptResult : ContentResult
{
    public JavaScriptResult(string script)
    {
        this.Content = script;
        this.ContentType = "application/javascript";
    }
}

Upvotes: 11

Related Questions