加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

View组件替代ajax刷新

发布时间:2020-12-16 03:08:28 所属栏目:百科 来源:网络整理
导读:我有一个viewcomponent包含嵌入各种页面的一些可重用的业务逻辑.这一直很好.但是,我现在需要使用ajax刷新viewcomponent. 有没有办法实现这个目标?从我读过的内容来看,这是不可能的,尽管这些信息有点过时了. 如果不可能,最好的选择是什么? 在beta7上,现在可
我有一个viewcomponent包含嵌入各种页面的一些可重用的业务逻辑.这一直很好.但是,我现在需要使用ajax刷新viewcomponent.

有没有办法实现这个目标?从我读过的内容来看,这是不可能的,尽管这些信息有点过时了.
如果不可能,最好的选择是什么?

在beta7上,现在可以直接从控制器返回ViewComponent.检查 the announcement的MVC / Razor部分

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.

所以你可以有一个像这样的简单视图组件:

[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}");
    }
}

在控制器中创建一个方法,如:

public IActionResult MyViewComponent()
{
    return ViewComponent("MyViewComponent");
}

并且比我的快速和肮脏的ajax刷新做得更好:

var container = $("#myComponentContainer");
var refreshComponent = function () {
    $.get("/Home/MyViewComponent",function (data) { container.html(data); });
};

$(function () { window.setInterval(refreshComponent,1000); });

当然,在beta7之前你可以创建一个视图作为@eedam建议的解决方法或使用these answers中描述的方法

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读