ASP.NET MVC - 返回 JavaScriptResult 不起作用
如果我尝试从我的控制器返回一些 JavaScript,如下所示:
public ActionResult DoSomething()
{
return JavaScript("alert('Hello world!');");
}
我没有在浏览器中查看警报消息,但我从名为操作的页面(在我的例子中是 register.js)收到 .js 脚本的下载请求。怎么了?
If I try to return some JavaScript from my Controller like this:
public ActionResult DoSomething()
{
return JavaScript("alert('Hello world!');");
}
I do not view the alert message in my browser, but I get a download request for a .js script from the page named as the action (register.js in my case). What is wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
当将结果作为
JavaScriptResult
返回时,我遇到了类似的问题,指定的 JavaScript 未执行。就我而言,JavaScript 内容在解决方案是使用
Content()
方法将 JavaScript 作为ContentResult
返回。所以尝试一下:我在 ASP.NET 论坛上找到了答案。请查看以下链接中 Bruce 的回答,以更完整地解释为什么这样做:
Return JavascriptResult Not工作
I had a similar problem with the specified JavaScript not executing when returning the result as a
JavaScriptResult
. In my case, the JavaScript content was rendering as text inside<pre>
tags.The solution is to return the JavaScript as a
ContentResult
, by using theContent()
method. So try:I found the answer on the ASP.NET forums. Have a look at Bruce's answer at the following link for a more complete explanation of why it gets done this way:
Return JavascriptResult Not Working
我不会返回 Javascript,我会返回
Content
,然后在页面上,我会将该内容转换为警报:I would not return Javascript, I would return
Content
, then on the page, I would convert that content to an alert:尝试下面的方法。
Try the below.
如果您需要使用 JavaScriptResult 返回 js 代码,请记住您的操作应该通过 ajax 调用来调用。通过 Html.Actionlink 或其他控件直接调用此操作会导致显示脚本文本而不是运行脚本。所以你需要在你的view中添加一段js代码:
并在MyController中添加你的action:
If you need to return a js code using JavaScriptResult, keep in mind that your action should be called via ajax call. Calling this action via Html.Actionlink or other controls directly, results in showing your script text instead of running the script. So you need to add a js code in your view:
and your action in MyController:
当您从视图调用操作时,请确保使用
@Ajax.ActionLink
而不是@Html.ActionLink
辅助方法。然后 JavaScript 将正确呈现并显示您的警报。When you are calling your action from the view, make sure you use
@Ajax.ActionLink
instead of the@Html.ActionLink
helper method. The JavaScript will then render correctly and your alert will display.