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

Hel*_*123 6 asp.net-mvc razor razor-pages

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

例子:

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

      public IActionResult OnGetFetchCreateMeetingPartial()
          {
             return Partial("_CreateMeetingPartial", new ManipulationDto());
          }
}
Run Code Online (Sandbox Code Playgroud)

我的部分视图设置如下:

@using Models.ManipulationModels
@model ManipulationDto
Run Code Online (Sandbox Code Playgroud)

这是一个部分页面,所以我没有使用 @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'.
Run Code Online (Sandbox Code Playgroud)

我不是在用我的剃须刀页面调用部分。我直接返回一个部分页面,因为我在 javascript 模式中使用返回的数据。甚至可以覆盖这种行为吗?默认情况下,它总是期望传入基础PageModel(即BoardMeetingsModel)。

我很惊讶,即使我明确地传递了一个存在的模型,局部视图仍然期待一个页面模型,而不是我为局部视图明确声明的模型。

Xee*_*vis 7

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

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

就换这个

return Partial("_CreateMeetingPartial", new ManipulationDto());
Run Code Online (Sandbox Code Playgroud)

有了这个

return Partial("_CreateMeetingPartial", new ManipulationDto());
Run Code Online (Sandbox Code Playgroud)

  • 天哪,我不敢相信它没有写在更引人注目的地方。我浪费了一天的时间试图找出问题所在,和往常一样,我最终发现它是一个在此版本中未修复的错误...不过还是谢谢你。 (2认同)

Hel*_*123 3

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

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

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
         }
}
Run Code Online (Sandbox Code Playgroud)