ViewComponent не может быть загружен непосредственно в InvokeAsyn c в js, он получит соответствующий html при загрузке вашей страницы, а не при запуске события щелчка, поэтому ваша страница будет загружаться в течение длительного времени, что возникает из-за ошибки в вашем js.
Чтобы реализовать событие щелчка для загрузки представления компонента представления, вам необходимо использовать ajax get request
в событии щелчка, чтобы применить к контроллеру к 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());
}
}
Здесь результат теста: