15

Anyone have any examples of javascript actionresults? I am having a hard time getting the script to execute once it has been returned. Thanks

2
  • Could you elaborate a little bit? Commented 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. Commented Aug 21, 2009 at 14:54

3 Answers 3

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);   
}  
Sign up to request clarification or add additional context in comments.

3 Comments

Just 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.
Are Javascript ActionResults their way of handling JsonP results or did they handle JsonP in some other way?
@Dr.Zim I think you would want to use the Json(...) method for that.
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 };
}

Comments

0

This might work..

 public ActionResult Search(string name)
    {
        // var someScript = Server.HtmlEncode("<script>alert('Hello')</script>");

        return  Content("<script>alert('Hello')</script>" );
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.