具有多个模型的 MVC 局部视图

MVC Partial view having more than one model

我有一个对象的树结构(如下图所示)。 类 Descendant1Descendant2 的查看方式与 Form class(根 class)相同。我想为此创建一个局部视图,但是,我需要在视图中有一个模型,因为我正在使用模型中的属性(例如来自根的名称 class)

这是我要在局部视图中的FormView代码:

<div>
   @foreach (var subForm in Model.SubForms)
{
    Html.RenderPartial(partialView, subForm);
}
<div>@Model.Name</div>
</div>

我想知道是否可以创建一个可以有多个模型的局部视图?我是否为所有后代 class 一起创建一个控制器?否则,您有什么想法可以继续吗?

I was wondering if it was possible to create a partial view that can have multiple models?

是的,为这 3 个 类 创建一个视图模型。下面的示例名为 FormViewModel.

public class FormViewModel{
   public class Descendant1 {get;set;}
   public class Descendant2 {get;set;}
   public class Descendant3 {get;set;}
}

那么在你看来你可以这样做;

@foreach (var subForm in Model.SubForms)
{
   FormViewModel fmv = new FormViewModel();

   // access its class properties
   fmv.Descendant1.SubForms.Add(new Form(){ // assign properties });

   // pass the view model to the partial view
   Html.RenderPartial(partialView, fmv);
}