6

In reference to Viewcomponent alternative for ajax refresh. I can't get the ajax to refresh in MVC6. The JavaScript container finds the Div value but the data is not updating. Any ideas would be appreciated!

ViewComponent - Default.cshtml:

@model IEnumerable<My.Models.Queue>
@foreach (var item in Model)
{
  @item.Queue
}

Index.cshtml:

<div id="Queue" class="blink">@Component.Invoke("Queue")</div>

javascript:

var container = document.getElementById("Queue");
var refreshComponent = function () {
$.get("Shared/Components/Queue", function (data) { container[data]; });};
$(function () { window.setInterval(refreshComponent, 1000); });
Community
  • 1
  • 1
dmli
  • 63
  • 1
  • 3

1 Answers1

6

You can't make Ajax request directly to the ViewComponent, but you can invoke it from any Controller's method like it's described in post that you mentioned in your question.

So you should create a simple Controller's method like:

public IActionResult QueueViewComponent()
{
    return ViewComponent("QueueViewComponent");
}

And call it from your JavaScript:

var container = $("#queueComponentContainer");
var refreshComponent = function () {
    $.get("/Home/QueueViewComponent", function (data) { container.html(data); });
};

$(function () { window.setInterval(refreshComponent, 1000); });

Where the Home is a Controller's name of your newly created method.

Community
  • 1
  • 1
  • Thank you Sami Kuhmonen. I will try this. I have been getting by with just refreshing the entire window with JavaScript rather than just the data component. – dmli Apr 30 '16 at 04:19