如何从Core 2 RazorPage ViewModel处理程序返回PartialView

问题描述:

在Asp.Net MVC中,您可以通过执行以下操作轻松返回部分视图:

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

return PartialView("ModelName", Model);

这是如何在RazorPage ViewModel处理程序上完成的?

How is this done on a RazorPage ViewModel Handler?

我知道了.它不像在MVC中那样直接.您必须创建一个空的ViewDataDictionary(),然后将其Model属性设置为零件的已填充模型.

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.

查看模型/处理程序

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

我现在可以通过ajax GET调用此处理程序,并使其返回部分的HTML.然后,我可以设置部分的div并按预期刷新部分.

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.

这是我正在拨打的AJAX电话:

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