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?
Content-Type
astext/plain
? – CarvenViewData["sayhello"] = "alert('hello');"
then from View: head tag<script>@Html.Raw(ViewData["sayhello"].ToString())</script>
– Lengthwise