Here is my partial view:
这是我的部分观点:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<script type="text/javascript">
function myFunction() { .... }
</script>
....other html content ...
On my page, I have a link that calls a controller action to render the partial view:
在我的页面上,我有一个链接调用控制器操作来呈现局部视图:
<%= Ajax.ActionLink(..., new AjaxOptions { ..., OnSuccess = "myFunction" }) %>
This is my controller action: ... return PartialView("TestControl"); ...
这是我的控制器动作:...返回PartialView(“TestControl”); ...
I thought that this is pretty straight forward. Unfortunately, I get the JavaScript error:
我认为这很简单。不幸的是,我收到了JavaScript错误:
Microsoft JScript runtime error: 'myFunction' is undefined.
Microsoft JScript运行时错误:'myFunction'未定义。
When I check the generated page source after the AJAX call, I can see myFunction
in the source. However, within AJAX's OnSuccess
, somehow it does not know about this function. Is there anything I have missed? Is there any way that I can call the script that are part of the partial view that is loaded via AJAX? (I have tried to use eval()
, somehow I could not resolve the function either.)
当我在AJAX调用之后检查生成的页面源时,我可以在源代码中看到myFunction。但是,在AJAX的OnSuccess中,不知何故它不知道这个函数。有什么我错过了吗?有什么方法可以调用脚本,它是通过AJAX加载的局部视图的一部分? (我试图使用eval(),不知何故我无法解析该函数。)
Thanks in advance.
提前致谢。
1 个解决方案
#1
OnSuccess may have happened before the injection of the partial view into the DOM; you might be better off calling myFunction
immediately after defining it:
OnSuccess可能在将部分视图注入DOM之前发生;你可能最好在定义之后立即调用myFunction:
function myFunction(){
//code here
}
myFunction();
That way, myFunction
gets invoked immediately after its definition (which, because the script reference is injected into the DOM by the partial view logic, is as soon as possible after the actual update of the partial view).
这样,myFunction在其定义之后立即被调用(因为部分视图逻辑将脚本引用注入到DOM中,所以在实际更新局部视图之后会尽快调用它)。
If myFunction
operates on the content of the partial view, you may have to move the script reference to the end of the partial view so that the DOM on which it operates is rendered before the JS is executed.
如果myFunction对部分视图的内容进行操作,则可能必须将脚本引用移动到局部视图的末尾,以便在执行JS之前呈现其操作的DOM。
#1
OnSuccess may have happened before the injection of the partial view into the DOM; you might be better off calling myFunction
immediately after defining it:
OnSuccess可能在将部分视图注入DOM之前发生;你可能最好在定义之后立即调用myFunction:
function myFunction(){
//code here
}
myFunction();
That way, myFunction
gets invoked immediately after its definition (which, because the script reference is injected into the DOM by the partial view logic, is as soon as possible after the actual update of the partial view).
这样,myFunction在其定义之后立即被调用(因为部分视图逻辑将脚本引用注入到DOM中,所以在实际更新局部视图之后会尽快调用它)。
If myFunction
operates on the content of the partial view, you may have to move the script reference to the end of the partial view so that the DOM on which it operates is rendered before the JS is executed.
如果myFunction对部分视图的内容进行操作,则可能必须将脚本引用移动到局部视图的末尾,以便在执行JS之前呈现其操作的DOM。