How to return a PartialView from Core 2 RazorPage ViewModel Handler

二次信任 提交于 2019-12-01 04:18:58
TechFisher

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);
    }
});

Thanks alot to TechFisher for figuring it out, here is a bit cleaner example.

public IActionResult OnGetTestPartial()
{
    return new PartialViewResult()
    {
        ViewName = "Test",
        ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary())
        {
            Model = new TestPartialData { Data = "inputhere" },
        }
    };
}

Partial view in a file name "Test.cshtml" in the same folder as the above class.

@using YourNamespace
@model TestPartialData

<div>Hello, model value: @Model.Data</div>

Load it async with jquery

$("#someHtmlElementId").load("Your/Path/TestPartial");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!