If I try to return some JavaScript from my Controller like this:
public ActionResult DoSomething()
{
return JavaScript("alert('Hello world!');");
}
I do not view the alert message in my browser, but I get a download request for a .js script from the page named as the action (register.js in my case). What is wrong?
I had a similar problem with the specified JavaScript not executing when returning the result as a JavaScriptResult
. In my case, the JavaScript content was rendering as text inside <pre>
tags.
The solution is to return the JavaScript as a ContentResult
, by using the Content()
method. So try:
public ActionResult DoSomething()
{
return Content("<script language='javascript' type='text/javascript'>alert('Hello world!');</script>");
}
I found the answer on the ASP.NET forums. Have a look at Bruce's answer at the following link for a more complete explanation of why it gets done this way:
Return JavascriptResult Not Working
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With