問題描述
我有一個視圖組件,其中包含一些嵌入到各個頁面中的可重用業務邏輯.這一直運作良好.但是,我現在需要使用 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 替代方案的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!