views:

415

answers:

1

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"); ...

I thought that this is pretty straight forward. Unfortunately, I get the JavaScript error:

Microsoft JScript runtime error: 'myFunction' is undefined.

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.)

Thanks in advanced.

A: 

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:

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).

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.

DDaviesBrackett
I actually do not know how to call it directly: I need wait the ajax request finished before I can do so. Could you show me how to do so? Thanks.
answer edited for clarity. Thanks for the followup!
DDaviesBrackett