ajax 刷新的视图组件替代方案

Viewcomponent alternative for ajax refresh

我有一个视图组件,其中包含一些嵌入各种页面的可重用业务逻辑。这一直很好用。但是,我现在需要使用 ajax 刷​​新视图组件。

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

在 beta7 上,现在可以直接从控制器 return 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.

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

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

在控制器中创建一个方法,例如:

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 之前,您可以按照@eedam 建议的解决方法创建一个视图,或者使用

中描述的方法