简体   繁体   中英

MVC3 - Ajax actionlink - OnBegin, onComplete

Using MVC3, C#, and the Razor View Engine: I have a form that has an Ajax Action link. In the options I'm trying to specify OnBegin and OnComplete javascript function calls. In this question, I took out the meat of the functions and simply added alerts so that I could verify that the functions where being hit. What I really want to do with these functions is to use $.blockUI for the duration of the ajax call.

The pertinent code looks like this:

@Ajax.ActionLink("my test link", "myAction", new { Controller = "myController" }, new AjaxOptions { OnBegin = "ajaxStart", OnComplete = "ajaxStop" })

<script type="text/javascript">
    function ajaxStart() {
        alert("start");
    }

    function ajaxStop() {
        alert("stop");
    }

</script>

For some reason, the two functions never get called as specified. I have tried it with and without the parentheses, sucha as this:

@Ajax.ActionLink("my test link", "myAction", new { Controller = "myController" }, new AjaxOptions { OnBegin = "ajaxStart()", OnComplete = "ajaxStop()" })

Neither work.

Any ideas?

Thanks, Tony

Make sure you have included the following script to your page:

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>

and that you have enabled unobtrusive ajax in your web.config:

<appSettings>
    ...
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>

In ASP.NET MVC 3 unobtrusive javascript is used with jQuery so uif you don't include the proper scripts, the HTML5 data-* attributes that are emitted by the html helpers are not interpreted and there is no AJAX request being sent.

You can try to put the <script> bloc before the Ajax.ActionLink method call. Use this syntax for the ajax link:

@Ajax.ActionLink("my test link", "myAction", "myController", new AjaxOptions { OnBegin = "ajaxStart", OnComplete = "ajaxStop" })

and remember to put the import of jquery.unobtrusive-ajax.min.js in your view or in _Layout.cshtml

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM