[英]How to render a partial view asynchronously
Can a partial view be rendered asynchronously? 部分视图可以异步渲染吗?
I have a partial view that needs to render blog posts. 我有部分视图需要呈现博客帖子。 The blog posts are returned asynchronously.
博客文章以异步方式返回。
In my _Layout
file I render my partial footer _Footer
. 在我的
_Layout
文件中,我渲染了我的部分页脚_Footer
。 In _Footer
I have the following markup: 在
_Footer
我有以下标记:
@Html.Action("FooterLatestBlogPosts", "Common")
So in my Common
controller I have the following action method: 所以在我的
Common
控制器中,我有以下操作方法:
public async Task<ActionResult> FooterLatestBlogPosts()
{
List<ArticleDTO> articleDTOs = await articleTask.GetAllAsync();
return PartialView(articleDTOs);
}
In my FooterLatestBlogPosts
partial view I have the following: 在我的
FooterLatestBlogPosts
局部视图中,我有以下内容:
@model List<MyProject.Application.DTO.ArticleDTO>
@if (Model.Count > 0)
{
<ul class="list-unstyled">
@foreach (var articleDTO in Model)
{
<li>@articleDTO.Title</li>
}
</ul>
}
I'm getting an error: 我收到一个错误:
Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper'
Should I rather just create a synchronous mthod to bring back my data? 我是否应该创建一个同步方法来恢复我的数据?
First of all you need to use Html.Partial
as suggested by @buffjape. 首先,您需要使用
Html.Partial
建议的Html.Partial。 If your partial view is not in Shared
folder you need to specify the path to the view 如果部分视图不在
Shared
文件夹中,则需要指定视图的路径
@Html.Partial("~/Views/Common/FooterLatestBlogPosts", yourModel)
However in this case your view is still loaded synchronously. 但是在这种情况下,您的视图仍然是同步加载的。 To load it in async way you need to load it via jQuery.
要以异步方式加载它,您需要通过jQuery加载它。 Article Improve perceived performance of ASP.NET MVC websites with asynchronous partial views gives a very good description on how to achieve it.
文章使用异步部分视图提高ASP.NET MVC网站的感知性能,可以很好地描述如何实现它。
Also replace your Html.Render
with 同时用你的
Html.Render
替换
$(document).ready(function(){
$("#yourContainer").load('@Url.Action("FooterLatestBlogPosts", "Common")')
});
I went with the answer in the post that @buffjape suggested: 我在@buffjape建议的帖子中回答了答案:
Async PartialView causes "HttpServerUtility.Execute blocked..." exception Async PartialView导致“HttpServerUtility.Execute被阻止...”异常
I changed my methods all to synchronous. 我将我的方法全部改为同步。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.