问题描述
我有一个viewcomponent,其中包含一些可重用的业务逻辑,这些逻辑嵌入到各个页面中。这一直很好。但是,我现在需要使用ajax刷新viewcomponent。
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
因此您可以拥有一个简单的视图像这样的组件:
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替代方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!