ASP.NET MVC Javascript ActionResult

前端 未结 3 1750
我寻月下人不归
我寻月下人不归 2020-12-09 18:10

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

相关标签:
3条回答
  • 2020-12-09 18:12

    This might work..

     public ActionResult Search(string name)
        {
            // var someScript = Server.HtmlEncode("<script>alert('Hello')</script>");
    
            return  Content("<script>alert('Hello')</script>" );
        }
    
    0 讨论(0)
  • 2020-12-09 18:22

    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);   
    }  
    
    0 讨论(0)
  • 2020-12-09 18:30

    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 };
    }
    
    0 讨论(0)
提交回复
热议问题