gpt4 book ai didi

c# - ViewComponents 不是异步的

转载 作者:行者123 更新时间:2023-11-30 13:18:56 28 4
gpt4 key购买 nike

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

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

我认为 ViewComponent.InvokeAsync() 方法将相对于主页异步呈现。但事实并非如此。为了实现这一点,我们需要按照说明使用 AJAX here .

最佳答案

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

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

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

并且此代码将阻塞,直到 itemsTask 完成。

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);
}

服务器端异步让我们在等待其他服务器端任务完成时在服务器上做额外的工作。

AJAX View 组件

要在 Web 浏览器中部分呈现页面,我们需要使用客户端 AJAX。在下面的示例中,我们使用 AJAX 调用 /Home/GetHelloWorld 并在 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>

localhost:5000/index.html

A unordered list that shows the string array.

关于c# - ViewComponents 不是异步的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36024748/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com