我尝试使用 javascript 调用 ViewComponent 来促进页面加载,现在我使用 razor 调用 ViewComponent 但页面加载时间很长,怎么办?
这是 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());
}
和方法调用(jQuery):
<script>
$(document).ready(function () {
$('#viewallfollowers').click(
function () {
$("#followersrefresh").load("@await Component.InvokeAsync("Follower", new { id=Model.ApplicationUser.Id })");
});
});
</script>
最佳答案
ViewComponent不能直接在js中的InvokeAsync中加载,它会在你的页面加载时获取相应的html,而不是在点击事件触发时获取相应的html,所以你的页面会加载很长时间,那是因为你的错误js。
为了实现点击事件加载ViewComponent View ,需要在点击事件中使用ajax get请求
申请到 Controller 返回html
View 组件的代码。
Controller :
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,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61602974/