Search code examples
asp.net-corerazor-pagesasp.net-core-viewcomponent

Razor Pages - Is it possible to route to a View Component for AJAX refresh


Context:

I have a section of a view that I want to update on a regular interval via JS.

What I have done so far:

Using the information given in: Viewcomponent alternative for ajax refresh

  • created a view component that encapsulates the region that I want to refresh
  • attempted to create a custom route to a view component as follows

options.Conventions.AddPageRoute("/Components/ViewComponent/default", "FriendlyRouteAlias");

  • use the following script to attempt to load the (updated) view component and inject the value into a div:

<script>
    var container = $(".DataToUpdate");
    var refreshComponent = function () {
        $.get("Route/to/view/component", function (data) { container.html(data); });
    };

    $(function () { window.setInterval(refreshComponent, 1000); });
</script>

Is it even possible to load a View Component this way or should I be looking at another way of accomplishing this?


Solution

  • As the commenters suggested, I was able to get it working by using an MVC controller action to return the view component directly. I will add that I used an MVC controller rather than an API controller because I was dealing with a view rather than data. (see Difference between ApiController and Controller in ASP.NET MVC)