asp.net-mvc ASP.NET MVC Javascript ActionResult

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1312408/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-07 23:47:17  来源:igfitidea点击:

ASP.NET MVC Javascript ActionResult

asp.net-mvc

提问by Joseph

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

任何人都有javascript actionresults的例子?一旦脚本返回,我很难让脚本执行。谢谢

回答by Joseph

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);   
}  

回答by Greg Gum

The only way I have found to return a JavascriptResult and execute it on the client is with JQuery:

我发现返回 JavascriptResult 并在客户端执行它的唯一方法是使用 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 };
}

回答by Gaurav Krishn

This might work..

这可能有效..

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

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