Viewcomponent alternative for ajax refresh(用于 ajax 刷新的 Viewcomponent 替代方案)
问题描述
我有一个视图组件,其中包含一些嵌入到各个页面中的可重用业务逻辑.这一直运作良好.但是,我现在需要使用 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 替代方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:用于 ajax 刷新的 Viewcomponent 替代方案
基础教程推荐
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- 直接将值设置为滑块 2022-01-01