Search code examples
ajaxasp.net-core-mvcasp.net-core-viewcomponent

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?


Solution

  • 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