Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
779 views
in Technique[技术] by (71.8m points)

asp.net core mvc - Viewcomponent alternative for ajax refresh

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

On beta7 it is now possible to return a ViewComponent directly from a controller. Check the MVC/Razor section of the announcement

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

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

Of course, prior to beta7 you could create a view as the workaround suggested by @eedam or use the approach described in these answers


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...