Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC - Returning JavaScriptResult doesn't work

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?

like image 976
User907863 Avatar asked Sep 01 '11 13:09

User907863


1 Answers

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

like image 176
Carl Heinrich Hancke Avatar answered Nov 15 '22 07:11

Carl Heinrich Hancke