Razor Pages - 无法将不同的模型传递给页面处理程序中的部分视图

Razor Pages - Can't pass different model to partial view within a page handler

我不太确定这是否可行,但想检查一下。我有一个具有几种不同处理程序方法的剃刀页面。在其中一些中,我 return 部分视图结果。

示例:

public class BoardMeetingsModel : PageModel
{ 
      //ctor
      //properties

      public IActionResult OnGetFetchCreateMeetingPartial()
          {
             return Partial("_CreateMeetingPartial", new ManipulationDto());
          }
}

我的局部视图设置如下:

@using Models.ManipulationModels
@model ManipulationDto

这是一个部分页面,所以我没有使用 @page 指令(部分页面被命名为 _CreateMeetingPartial.cshtml。当我传入 ManipulationModel 时,我 运行 进入以下错误

The model item passed into the ViewDataDictionary is of type 'Models.ManipulationDto', but this ViewDataDictionary instance requires a model item of type 'Pages.BoardMeetingsModel'.

我不会用我的剃须刀页面调用部分。我直接 return 使用部分页面,因为我在 javascript 模态中使用 returned 数据。甚至可以覆盖此行为吗?默认情况下,它始终期望传入基础 PageModel(即 BoardMeetingsModel)。

令我惊讶的是,即使我显式传递了一个存在的模型,部分视图仍然需要一个页面模型,而不是我为部分视图明确声明的模型。

要解决上述问题,我必须执行以下操作。请注意,我的 ManipulationDto 属性 上没有 [BindProperty] 属性,因为我的页面上有多个模型。如果你有多个模型并且你有验证(例如必需的属性),所有这些都将在与 MVC 不同的剃须刀页面中触发。在我的案例中处理它的方法是直接将模型作为参数传递,但还要确保有一个 public 属性 我可以分配所有值以防模型状态验证失败。

如果您没有多个独特的模型,每个模型都有自己的验证,您可以只应用 bind属性 属性而不用担心。

public class BoardMeetingsModel : PageModel
{ 
      //this gets initialized to a new empty object in the constructor (i.e. MeetingToManipulate = new ManipulationDto();)
      public ManipulationDto MeetingToManipulate { get; set; }

      //ctor
      //properties

      public IActionResult OnGetFetchCreateMeetingPartial(ManipulationDto meetingToManipulate)
          {
             //send the page model as the object as razor pages expects 
             //the page model as the object value for partial result
             return Partial("_CreateMeetingPartial", this);
          }

      public async Task<IActionResult> OnPostCreateMeetingAsync(CancellationToken cancellationToken, ManipulationDto MeetingToCreate)
        {
            if (!ModelState.IsValid)
            {
                //set the pagemodel property to be the values submitted by the user
                //not doing this will cause all model state errors to be lost
                this.MeetingToManipulate = MeetingToCreate;
                return Partial("_CreateMeetingPartial", this);
            }
            //else continue
         }
}

这似乎是 ASP.NET Core 2.2 中新引入的 Partial() 中的错误,其中模型参数似乎完全多余,因为 "this" 是它唯一接受的参数。

但如果您使用 PartialViewResult(),它将起作用。应该比公认的解决方案更简单、更易读。

就换这个

return Partial("_CreateMeetingPartial", new ManipulationDto());

有了这个

return new PartialViewResult
{
    ViewName = "_CreateMeetingPartial",
    ViewData = new ViewDataDictionary<ManipulationDto>(ViewData, new ManipulationDto())
};