Ajax.ActionLink alternative with mvc core

余生颓废 提交于 2019-12-01 07:37:24

ViewComponent's are not replacement of ajaxified links. It works more like Html.Action calls to include child actions to your pages (Ex : Loading a menu bar). This will be executed when razor executes the page for the view.

As of this writing, there is no official support for ajax action link alternative in aspnet core.

But the good thing is that, we can do the ajaxified stuff with very little jQuery/javascript code. You can do this with the existing Anchor tag helper

<a asp-action="GetEnvironment"  asp-route-id="@Model.Id" asp-controller="Environments" 
                                 data-target="environment-container" id="aUpdate">Update</a>
<div id="environment-container"></div>

In the javascript code, just listen to the link click and make the call and update the DOM.

$(function(){

   $("#aUpdate").click(function(e){

     e.preventDefault();
     var _this=$(this);
     $.get(_this.attr("href"),function(res){
         $('#'+_this.data("target")).html(res);
     });

   });

});

Since you are passing the parameter in querystring, you can use the jQuery load method as well.

$(function(){

   $("#aUpdate").click(function(e){

     e.preventDefault();
     $('#' + $(this).data("target")).load($(this).attr("href"));

   });

});
user6272884

You can use a tag as follows:

<a data-ajax="true"
                   data-ajax-loading="#loading"
                   data-ajax-mode="replace"
                   data-ajax-update="#editBid"
                   href='@Url.Action("_EditBid", "Bids", new { bidId = Model.BidId, bidType = Model.BidTypeName })'
                   class="TopIcons">

Make sure you have in your _Layout.cshtml page the following script tag at the end of the body tag:

<script src="~/lib/jquery/jquery.unobtrusive-ajax/jquery.unobtrusive-ajax.js"></script>

Use tag helpers instead and make sure to include _ViewImport in your views folder.

Note: Make sure to use document.getElementsByName if there are several links pointing to different pages that will update your DIV.

Example - Razor Page

<script type="text/javascript" language="javascript">
    $(function () {
        var myEl = document.getElementsByName('theName');
        $(myEl).click(function (e) {

            e.preventDefault();
            var _this = $(this);
            $.get(_this.attr("href"), function (res) {
                $('#' + _this.data("target")).html(res);
            });
        });
    });
</script>
<a asp-action="Index" asp-controller="Battle" data-target="divReplacable" name="theName" >Session</a>
<a asp-action="Index" asp-controller="Peace" data-target="divReplacable" name="theName" >Session</a>


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