Anyone have any examples of javascript actionresults? I am having a hard time getting the script to execute once it has been returned. Thanks
Asked
Active
Viewed 3.1k times
15
-
Could you elaborate a little bit? – Jimmeh Aug 21 '09 at 14:52
-
Sure let's say I am returning the following from an action. Javascript("alert('Hello World');"); Instead of an alert dialog I am getting a page that has "alert('Hello World')" displayed in it. – Aug 21 '09 at 14:54
3 Answers
16
Here's an example I found on a blog post, which actually describes it as an anti-pattern, because the Controller has to have in-depth knowledge of the View in order to function.
public ActionResult DoSomething() {
string s = "$('#some-div').html('Updated!');";
return JavaScript(s);
}

Joey Gennari
- 2,361
- 17
- 26

Joseph
- 25,330
- 8
- 76
- 125
-
10Just wanted to add for those viewing this in the future. It appears to me that the javascript result will only be executed when the action is called via ajax. Calling this action via an Html.Actionlink will result in the text of the script being returned, but not executed. – Aug 21 '09 at 17:49
-
Are Javascript ActionResults their way of handling JsonP results or did they handle JsonP in some other way? – Zachary Scott Jul 15 '12 at 21:45
-
2
The only way I have found to return a JavascriptResult and execute it on the client is with JQuery:
<script>
$(document).ready(function () {
$("button").click(function () {
$.getScript("/Home/ShowAlert");
});
});
</script>
<button>Use Ajax to get and then run a JavaScript</button>
In the controller:
public JavaScriptResult ShowAlert() {
var script = "alert('Hello');";
return new JavaScriptResult() { Script = script };
}

Greg Gum
- 33,478
- 39
- 162
- 233
0
This might work..
public ActionResult Search(string name)
{
// var someScript = Server.HtmlEncode("<script>alert('Hello')</script>");
return Content("<script>alert('Hello')</script>" );
}

Gaurav
- 437
- 1
- 6
- 15