czu*_*ski 17 ajax asp.net-core-mvc asp.net-core-viewcomponent
我有一个viewcomponent包含嵌入各种页面的一些可重用的业务逻辑.这一直很好.但是,我现在需要使用ajax刷新viewcomponent.
有没有办法实现这个目标?根据我的阅读,这是不可能的,虽然这些信息有点过时了.如果不可能,最好的选择是什么?
Dan*_*.G. 29
在beta7上,现在可以直接从控制器返回ViewComponent.检查公告的MVC/Razor部分
MVC中的新ViewComponentResult使得从动作返回ViewComponent的结果变得容易.这使您可以轻松地将ViewComponent的逻辑公开为独立端点.
所以你可以有一个像这样的简单视图组件:
[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}");
}
}
Run Code Online (Sandbox Code Playgroud)
在控制器中创建一个方法,如:
public IActionResult MyViewComponent()
{
return ViewComponent("MyViewComponent");
}
Run Code Online (Sandbox Code Playgroud)
并且做得比我的快速和肮脏的ajax刷新做得更好:
var container = $("#myComponentContainer");
var refreshComponent = function () {
$.get("/Home/MyViewComponent", function (data) { container.html(data); });
};
$(function () { window.setInterval(refreshComponent, 1000); });
Run Code Online (Sandbox Code Playgroud)
当然,在beta7之前你可以创建一个视图作为@eedam建议的解决方法或使用这些答案中描述的方法