ViewComponents不是异步的 [英] ViewComponents are not async

查看:154
本文介绍了ViewComponents不是异步的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用ViewComponents.InvokeAsync()功能,但是某种程度上这根本不是异步的.它正在等待组件代码呈现. http://docs.asp.net/zh/latest/mvc/views/view-components.html

I am trying to use the ViewComponents.InvokeAsync() feature, but somehow this is not async at all. It is waiting for the component code to render. http://docs.asp.net/en/latest/mvc/views/view-components.html

我的代码与上述示例中的代码非常相似.我正在使用在MVC 6中创建新应用程序时出现的布局页面.

My code is very much similar to the one explained in above example. I am using the layout page which comes when you create new application in MVC 6.

我认为ViewComponent.InvokeAsync()方法将相对于主页异步呈现.但事实并非如此.为了实现这一目标,我们需要使用此处中所述的AJAX

I thought that ViewComponent.InvokeAsync() method will render asynchronously with respect to the main page. But it does not. In order to achieve this, we need to use AJAX as explained here.

推荐答案

服务器端异步不是客户端异步

服务器端异步不会在Web浏览器中进行部分页面渲染.以下代码将阻塞,直到GetItemsAsync返回.

public async Task<IViewComponentResult> InvokeAsync()
{
    var items = await GetItemsAsync();
    return View(items);
}

此代码将阻塞,直到itemsTask完成.

And this code will block until the itemsTask completes.

public async Task<IViewComponentResult> InvokeAsync()
{
    var itemsTask = GetItemsAsync(maxPriority, isDone);

    // We can do some other work here,
    // while the itemsTask is still running.

    var items = await itemsTask;
    return View(items);
}

服务器端异步使我们可以在服务器上完成其他工作 ,同时我们还要等待其他服务器端任务完成.

Server side async lets us do additional work on the server while we wait for some other server side task to complete.

要在Web浏览器中部分呈现页面,我们需要使用客户端AJAX.在下面的示例中,我们使用AJAX调用/Home/GetHelloWorld并在body中呈现.

To partially render the page in the web browser, we need to use client side AJAX. In the following example, we use AJAX to call /Home/GetHelloWorld and render in in the body.

〜/HelloWorldViewComponent.cs

public class HelloWorldViewComponent : ViewComponent
{
    public IViewComponentResult Invoke()
    {
        var model = new string[]
        {
            "Hello", "from", "the", "view", "component."  
        };

        return View("Default", model);
    }     
}

〜/HomeController.cs

public class HomeController : Controller
{
    public IActionResult GetHelloWorld()
    {
        return ViewComponent("HelloWorld");
    }
}

〜/Views/Shared/Components/HelloWorld/Default.cshtml

@model string[]

<ul>
    @foreach(var item in Model)
    {
        <li>@item</li>
    }
</ul>

〜/wwwroot/index.html

<body>
<script src="js/jquery.min.js"></script>
<script>
    $.get("home/GetHelloWorld", function(data) {
        $("body").html(data);
    });
</script>
</body>

本地主机:5000/index.html

这篇关于ViewComponents不是异步的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆