用于 ajax 刷新的 Viewcomponent 替代方案 [英] Viewcomponent alternative for ajax refresh

查看:21
本文介绍了用于 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 替代方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆