Anyone have any examples of javascript actionresults? I am having a hard time getting the script to execute once it has been returned. Thanks
-
Could you elaborate a little bit?Jimmeh– Jimmeh2009-08-21 14:52:21 +00:00Commented Aug 21, 2009 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.Chris– Chris2009-08-21 14:54:31 +00:00Commented Aug 21, 2009 at 14:54
Add a comment
|
3 Answers
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);
}
3 Comments
Zachary Scott
Are Javascript ActionResults their way of handling JsonP results or did they handle JsonP in some other way?
Joseph
@Dr.Zim I think you would want to use the Json(...) method for that.
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 };
}