如何 return 来自 Core 2 Razor 页面 ViewModel 处理程序的局部视图

How to return a PartialView from Core 2 RazorPage ViewModel Handler

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

return PartialView("ModelName", Model);

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

我想通了。它不像在 MVC 中那样直接。您必须创建一个空的 ViewDataDictionary(),然后将其模型 属性 设置为部分填充的模型。

查看模型/处理程序

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 调用此处理程序并将其 return 部分 HTML。然后我可以按预期设置部分的 div 和部分刷新。

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

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

非常感谢 TechFisher 解决了这个问题,这里有一个更清晰的示例。

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

与上述 class.

在同一文件夹中的文件名 "Test.cshtml" 中的部分视图
@using YourNamespace
@model TestPartialData

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

与 jquery

异步加载
$("#someHtmlElementId").load("Your/Path/TestPartial");