Search code examples
jqueryajaxasp.net-corerazorasp.net-core-viewcomponent

Invoke ViewComponents using javascript


Im trying to Invoke ViewComponent using javascript to facilitate page loading,now i invoked viewcomponent using razor but the loading of page taking long time, how to do that?

Here is the method in controller:

public async Task<IViewComponentResult> InvokeAsync(string id)
{
    //var notifications = _context.Notifications.Include(m => m.ApplicationUser).Include(m => m.Sender).OrderByDescending(m => m.Id);

    return View(await _context.Follows.Include(f=>f.User.University).Include(f=>f.User.Faculty).Where(n=>n.FollowedUserId==id).ToListAsync());
}

and method call (jQuery):

<script>
    $(document).ready(function () {
        $('#viewallfollowers').click(
            function () {

                $("#followersrefresh").load("@await Component.InvokeAsync("Follower", new { id=Model.ApplicationUser.Id })");

              });
    });
</script>

Solution

  • ViewComponent cannot be loaded directly in InvokeAsync in js, it will get the corresponding html when your page loads instead of when the click event is triggered, so your page will load for a long time, that is because of an error in your js.

    In order to realize the click event to load the viewcomponent view, you need to use the ajax get request in the click event to apply to the controller to return the html code of the viewcomponent.

    Controller:

     public IActionResult GetMyViewComponent(string uid)
            {
                return ViewComponent("Follower", new { id = uid});//it will call Follower.cs InvokeAsync, and pass id to it.
            }
    

    View:

    @model WebApplication_core_mvc.Models.MyCompModel
    @{
        ViewData["Title"] = "Index";
        Layout = "~/Views/Shared/_Layout.cshtml";
    }
    
    <h1>Index</h1>
    
    @section Scripts{
        <script>
       $(document).ready(function () {
            $('#viewallfollowers').click(function () {
                {
                    $("#followersrefresh").empty();
                    var _url = '@Url.Action("GetMyViewComponent", "Home")';
                    $.ajax({
                        type: "GET",
                        url: _url,
                        data: { uid: $(this).prop("name") },
                        success: function (result) {
                            $("#followersrefresh").html(result);
                        },
                    });
                }
            });
        });
        </script>
    }
    <input id="viewallfollowers" type="button" value="button" name="@Model.ApplicationUser.Id"/>
    <div id="followersrefresh" >
    </div>
    

    ViewComponents.Follower.cs:

     public class Follower : ViewComponent
        {
            private readonly MyDbContext _context;
            public Follower(MyDbContext context)
            {
                _context = context;
            }
            public async Task<IViewComponentResult> InvokeAsync(string id)
            {
                return View(await _context.Follows.Include(f=>f.User.University).Include(f=>f.User.Faculty).Where(n=>n.FollowedUserId==id).ToListAsync());
            }
        }
    

    Here is the test result: enter image description here