在Asp.Net MVC中,您可以通过执行以下操作轻松返回部分视图:
return PartialView("ModelName", Model);
如何在RazorPage ViewModel处理程序上完成?
答案 0 :(得分:8)
我想出来了。它并不像MVC那样直截了当。您必须创建一个空的ViewDataDictionary()
,然后将其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。然后,我可以按预期设置部分&n; 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);
}
});
答案 1 :(得分:2)
非常感谢TechFisher弄清楚了,这里是一个更干净的示例。
public IActionResult OnGetTestPartial()
{
return new PartialViewResult()
{
ViewName = "Test",
ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary())
{
Model = new TestPartialData { Data = "inputhere" },
}
};
}
在与上述类相同的文件夹中的文件名“ Test.cshtml”中的局部视图。
@using YourNamespace
@model TestPartialData
<div>Hello, model value: @Model.Data</div>
使用jquery异步加载
$("#someHtmlElementId").load("Your/Path/TestPartial");