Viewcomponent alternative for ajax refresh
我有一个viewcomponent,其中包含嵌入在各个页面中的一些可重用的业务逻辑。 这一直很好。 但是,我现在需要使用ajax刷新视图组件。
有什么办法可以做到这一点? 从我所读的内容来看,这是不可能的,尽管该信息有些过时了。
如果不可能的话,最好的选择是什么?
在beta7上,现在可以直接从控制器返回ViewComponent。 查看公告的" MVC /剃刀"部分
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.
因此,您可以拥有一个像这样的简单视图组件:
1 2 3 4 5 6 7 8 9 | [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}"); } } |
在控制器中创建一个方法,例如:
1 2 3 4 | public IActionResult MyViewComponent() { return ViewComponent("MyViewComponent"); } |
并且比我快速又肮脏的ajax刷新做得更好:
1 2 3 4 5 6 | var container = $("#myComponentContainer"); var refreshComponent = function () { $.get("/Home/MyViewComponent", function (data) { container.html(data); }); }; $(function () { window.setInterval(refreshComponent, 1000); }); |
当然,在beta7之前,您可以创建视图作为@eedam建议的解决方法,也可以使用这些答案中描述的方法