Rewrite an asp.net mvc ajax actionlink as a jquery/ajax statement

北城余情 提交于 2019-12-30 11:21:11

问题


How would you rewrite this statement using Jquery + Ajax only? This code displays a link. When I click on it a view is returned into the StuffPanel id.

@{ AjaxOptions options = new AjaxOptions
           {
               InsertionMode = InsertionMode.Replace,
               UpdateTargetId = "StuffPanel",
               OnBegin = "OnBeginWork",
               OnComplete = "OnCompleteWork",
           };}
<p>@Ajax.ActionLink("show stuff", "Index", "Stuff", options)</p>

回答1:


Here you go:

<a href="/Index/Stuff" id="action">show stuff</a>

$(function() {
    $('#action').click(function(e) {
        e.preventDefault();
        var url = $(this).attr('href');
        $.ajax({
            url: url,
            beforeSend: OnBeginWork,
            complete: OnCompleteWork,
            success: function(html) {
                $('#StuffPanel').html(html);
            }
        });
    });
});

I'd recommend you keep the actionLink as all it's doing is getting the correct routing for you. Add an ID to it so that you can bind the click event easier, and then use the click event callback to fire the ajax call. Use the success function to replace the contents of #StuffPanel with the response.




回答2:


Based on the limited amount of information you have provided, something like this should get you going in the right direction:

$(function(){   
    $('#id-to-link').on('click',function(e){
        e.preventDefault();
        $.ajax('Index/Stuff',{
            type: 'POST',
            data: '{}',
            dataType: 'html',
            contentType: 'application/json; charset=utf-8',
            success: function(data){
                $('#StuffPanel').html(data);
            }
        });
    });
}

You'll have to check the data variable in the success callback. The HTML from the view will either be in data or in some property of data like data.d or data.message or something similar. Also, you should give your link a unique ID so you can bind your click event to it easily.



来源:https://stackoverflow.com/questions/10389740/rewrite-an-asp-net-mvc-ajax-actionlink-as-a-jquery-ajax-statement

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