我有一个视图组件,其中包含一些嵌入到各个页面中的可重用业务逻辑.这一直运作良好.但是,我现在需要使用 ajax 刷新视图组件.
I have a viewcomponent that contains some reusable business logic that embed in various pages. This has been working fine. However, I now have a requirement to refresh the viewcomponent using ajax.
有没有办法做到这一点?根据我的阅读,这是不可能的,尽管该信息有点过时了.如果不可能,最好的选择是什么?
Is there any way to accomplish this? From what I have read, it is not possible, although that info was a bit outdated. If it is not possible, what is the best alternative?
在 beta7 上,现在可以直接从控制器返回 ViewComponent.检查 公告
On beta7 it is now possible to return a ViewComponent directly from a controller. Check the MVC/Razor section of the announcement
MVC 中新增的 ViewComponentResult 使得返回结果变得容易来自动作的 ViewComponent.这使您可以轻松地暴露ViewComponent 作为独立端点的逻辑.
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.
所以你可以有一个像这样的简单视图组件:
So you could have a simple view component like this:
[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}");
}
}
在控制器中创建一个方法,例如:
Create a method in a controller like:
public IActionResult MyViewComponent()
{
return ViewComponent("MyViewComponent");
}
并且比我快速而肮脏的 ajax 刷新做得更好:
And do a better job than my quick and dirty ajax refresh:
var container = $("#myComponentContainer");
var refreshComponent = function () {
$.get("/Home/MyViewComponent", function (data) { container.html(data); });
};
$(function () { window.setInterval(refreshComponent, 1000); });
当然,在 beta7 之前,您可以创建一个视图作为@eedam 建议的解决方法,或者使用 这些答案
Of course, prior to beta7 you could create a view as the workaround suggested by @eedam or use the approach described in these answers
这篇关于用于 ajax 刷新的 Viewcomponent 替代方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!