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>
2
Answers
View component is essentially a razor page and a razor page renders html at run time. So, you can’t invoke it using js. But, you can do a redirect to a get action in your controller and return a view component. Check similar SO:
Invoke ViewComponent using javascript
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 toreturn the html
code of the viewcomponent.Controller:
View:
ViewComponents.Follower.cs:
Here is the test result: