javascriptc#jqueryajaxasp.net-core

How to refresh or reload a ViewComponent with Ajax in Asp.net Core 3.1?


I want FavoriteComponent to refresh when the "a" tag is clicked ?

Html :

<div id="favarite-user">
   
        @await Component.InvokeAsync("FavoriteComponent")        
</div>

Action Html :

<a id="add-fav" onclick="addfavorite('@product.Id')"></a>

Jquery :

 $.ajax({
    type: "post",
    url: '@Url.Action("AddFavorite", "Product")',
    data: { id: id },          
}).done(function (msg) {
    if (msg.status === 'added') {              
        $('#favarite-user').load(' #favarite-user')
    }

});

Controller:

 public IActionResult AddFavorite(Guid id)
    {           
        bool fav = _scope.AddFavorite(id, Guid.Parse(CurrentUserId));
        if (fav == true)
        {
            //return ViewComponent("FavoriteComponent");
          return Json(new { status = "added" });
        }
        return Json(new { status = "removed" });
    }   

Solution

  • This code worked for me:

    $.ajax({
        type: "post",
        url: '@Url.Action("AddFavorite", "Product")',
        data: { id: id },          
    }).done(function (msg) {
        if (msg.status === 'added') {              
            $('#favarite-user').load(' #favarite-user')
        }
    });