How to return a PartialView from Core 2 RazorPage ViewModel Handler

TechFisher picture TechFisher · Mar 8, 2018 · Viewed 8.9k times · Source

In Asp.Net MVC, you can easily return a partial view by doing the following:

return PartialView("ModelName", Model);

How is this done on a RazorPage ViewModel Handler?

Answer

TechFisher picture TechFisher · Mar 8, 2018

I figured this out. It is not nearly as straight forward as it is in MVC. You have to create an empty ViewDataDictionary() and then set its Model property to the partial's populated model.

View Model / Handler

public async Task<IActionResult> OnGetAsyncUpdateSearchResults(DateTime startDate, DateTime endDate, string selectedTypes)
{
    int[] types = selectedTypes.Split(",").Select(x => int.Parse(x)).ToArray();

    var inventory = await _itemService.GetFiltered(types, null, null, null, null, null, null, startDate, endDate.ToUniversalTime(), null, null, null, null, null, null, null);

    if (inventory != null)
    {
        SearchResultsGridPartialModel = new SearchResultsGridPartialModel();
        SearchResultsGridPartialModel.TotalCount = inventory.TotalCount;
        SearchResultsGridPartialModel.TotalPages = inventory.TotalPages;
        SearchResultsGridPartialModel.PageNumber = inventory.PageNumber;
        SearchResultsGridPartialModel.Items = inventory.Items;
    }

    var myViewData = new ViewDataDictionary(new Microsoft.AspNetCore.Mvc.ModelBinding.EmptyModelMetadataProvider(), new Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary()) { { "SearchResultsGridPartialModel", SearchResultsGridPartialModel } };
    myViewData.Model = SearchResultsGridPartialModel;

    PartialViewResult result = new PartialViewResult()
    {
        ViewName = "SearchResultsGridPartial",
        ViewData = myViewData,
    };

    return result;
}

I can now call this handler via ajax GET and have it return the partial's HTML. I can then set the partial's div and the partial refreshes as expected.

Here is the AJAX call I'm making:

var jsonData = { "startDate": startDate, "endDate": endDate, "selectedTypes": selectedTypesAsString };

$.ajax({
    type: 'GET',
    url: "searchresults/?handler=AsyncUpdateSearchResults",
    beforeSend: function (xhr) {
        xhr.setRequestHeader("XSRF-TOKEN", $('input:hidden[name="__RequestVerificationToken"]').val());
    },
    contentType: 'application/json; charset=utf-8"',
    data: jsonData,
    success: function (result) {
        $("#searchResultsGrid").html(result);
    },
    error: function (error) {
        console.log(error);
    }
});