moh*_*991 3 ajax jquery razor asp.net-core asp.net-core-viewcomponent
我试图使用javascript调用ViewComponent来促进页面加载,现在我使用razor调用了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());
}
Run Code Online (Sandbox Code Playgroud)
和方法调用(jQuery):
<script>
$(document).ready(function () {
$('#viewallfollowers').click(
function () {
$("#followersrefresh").load("@await Component.InvokeAsync("Follower", new { id=Model.ApplicationUser.Id })");
});
});
</script>
Run Code Online (Sandbox Code Playgroud)
ViewComponent不能直接在js的InvokeAsync中加载,它会在你的页面加载而不是点击事件被触发时获取相应的html,所以你的页面会加载很长时间,那是因为你的js出错了。
为了实现点击事件加载viewcomponent视图,需要ajax get request在click事件中使用 应用到controller到return the htmlviewcomponent的代码中。
控制器:
public IActionResult GetMyViewComponent(string uid)
{
return ViewComponent("Follower", new { id = uid});//it will call Follower.cs InvokeAsync, and pass id to it.
}
Run Code Online (Sandbox Code Playgroud)
看法:
@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>
Run Code Online (Sandbox Code Playgroud)
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());
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2884 次 |
| 最近记录: |