How to do this in Razor pages?
On page load I want to load a list of Cars into an object that I can later access when I load a partialview via an AJAX call.
When I run the code below (after I click the 'Load' button) the values of 'Cars' in OnGetCarPartial is null...
How do I maintain the value of 'Cars' between initial content page load and the subsequent AJAX call?
(Note the reason I want to do this, is that eventually I want _carService.ReadAll to run asynchronously in a thread on page load, updating the 'Cars' list every second, so whenever I load the partialview, I get the latest 'Cars' list without having to call _carService.ReadAll().)
PageModel:
namespace ApiTest.Pages.Cars
{
public class AjaxPartialModel : PageModel
{
private ICarService _carService;
public List<Car> Cars { get; set; }
public AjaxPartialModel(ICarService carService)
{
_carService = carService;
}
public async Task OnGetAsync()
{
if (Cars == null)
{
Cars = _carService.ReadAll();
}
}
public PartialViewResult OnGetCarPartial()
{
return Partial("_CarPartial", Cars);
}
}
}
Content page AJAX
@page
@model AjaxPartialModel
<p><button class="btn btn-primary" id="load">Load</button></p>
<div id="grid"></div>
@section scripts{
<script>
$(function () {
$('#load').on('click', function () {
$('#grid').load('/Cars/Index?handler=CarPartial');
});
});
</script>
}