gpt4 book ai didi

ajax - Ajax 刷新的 ViewComponent 替代方案

转载 作者:行者123 更新时间:2023-12-03 01:48:37 29 4
gpt4 key购买 nike

我有一个 View 组件,其中包含一些嵌入到各个页面中的可重用业务逻辑。这一直运作良好。但是,我现在需要使用 ajax 刷新 View 组件。

有什么办法可以实现这一点吗?据我所知,这是不可能的,尽管该信息有点过时了。如果不可能,最好的选择是什么?

最佳答案

在 beta7 中,现在可以直接从 Controller 返回 ViewComponent。检查 the announcement 的 MVC/Razor 部分

The new ViewComponentResult in MVC makes it easy to return the result of a ViewComponent from an action. This allows you to easily expose the logic of a ViewComponent as a standalone endpoint.

所以你可以有一个像这样的简单 View 组件:

[ViewComponent(Name = "MyViewComponent")]
public class MyViewComponent : ViewComponent
{
public IViewComponentResult Invoke()
{
var time = DateTime.Now.ToString("h:mm:ss");
return Content($"The current time is {time}");
}
}

在 Controller 中创建一个方法,例如:

public IActionResult MyViewComponent()
{
return ViewComponent("MyViewComponent");
}

并且比我快速而肮脏的 ajax 刷新做得更好:

var container = $("#myComponentContainer");
var refreshComponent = function () {
$.get("/Home/MyViewComponent", function (data) { container.html(data); });
};

$(function () { window.setInterval(refreshComponent, 1000); });

当然,在 beta7 之前,您可以创建一个 View 作为 @eedam 建议的解决方法,或者使用 these answers 中描述的方法。

关于ajax - Ajax 刷新的 ViewComponent 替代方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32618759/

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