MVC3 - Ajax actionlink - OnBegin, onComplete

≯℡__Kan透↙ 提交于 2019-12-10 13:43:33

问题


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


回答1:


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.




回答2:


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>


来源:https://stackoverflow.com/questions/7501896/mvc3-ajax-actionlink-onbegin-oncomplete

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!