用于 ajax 刷新的 Viewcomponent 替代方案

Viewcomponent alternative for ajax refresh(用于 ajax 刷新的 Viewcomponent 替代方案)
本文介绍了用于 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 替代方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Parsing XML namespaces?(解析 XML 命名空间?)
Storing HTML5 geolocation data(存储 HTML5 地理位置数据)
Allow just one click in class JQUERY(只允许在 JQUERY 类中单击一次)
How to click an element which is loaded through Ajax through webdriver within Chrome(如何在 Chrome 中单击通过 webdriver 通过 Ajax 加载的元素)
Caching issue with loading partial views into JQuery dialogs(将部分视图加载到 JQuery 对话框中的缓存问题)
jQuery UI datepicker opens automatically within dialog(jQuery UI datepicker 在对话框中自动打开)