我试图使用JavaScript调用ViewComponent来促进页面加载,现在我使用剃刀调用了viewComponent,但是页面加载需要很长时间,该怎么办?

这是控制器中的方法:

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());
}


和方法调用(jQuery):

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

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

              });
    });
</script>

最佳答案

ViewComponent不能直接在js的InvokeAsync中加载,它将在加载页面时(而不是在触发click事件时)获取相应的html,因此页面将加载很长时间,这是因为js中的错误。

为了实现单击事件以加载viewcomponent视图,您需要在click事件中使用ajax get request以将控制器应用于viewcomponent的return the html代码。

控制器:

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


视图:

@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());
        }
    }


这是测试结果:
jquery - 使用javascript调用ViewComponents-LMLPHP

10-02 16:29