Asp.net-Mvc

Razor Pages - 無法將不同的模型傳遞給頁面處理程序中的部分視圖

  • April 30, 2019

我不太確定這是否可行,但想檢查一下。我有一個剃須刀頁面,它有幾個不同的處理程序方法。在其中一些中,我返回部分視圖結果。

例子:

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'.

我不是用我的剃須刀頁面呼叫部分內容。我直接返回部分頁面,因為我正在使用 javascript 模式中的返回數據。甚至可以覆蓋這種行為嗎?預設情況下,它總是希望傳入基數PageModel(即BoardMeetingsModel)。

令我驚訝的是,即使我明確地傳遞了一個存在的模型,局部視圖仍然需要一個頁面模型,而不是我為局部視圖明確聲明的模型。

要解決上述問題,我必須在下面做。請注意,我沒有

$$ BindProperty $$我的 ManipulationDto 屬性上的屬性,因為我的頁面上有多個模型。如果您有多個模型並且您有驗證(例如必需的屬性),所有這些都將在不同於 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
        }
}

這似乎是Partial()ASP.NET Core 2.2 中新引入的錯誤,其中模型參數似乎是完全多餘的,因為“this”是它唯一會接受的東西。

但是,如果您使用PartialViewResult()它,它將起作用。應該比公認的解決方案更簡單、更易讀。

換這個就行

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

有了這個

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

引用自:https://stackoverflow.com/questions/54528437