【问题标题】:MVC Partial view having more than one model具有多个模型的 MVC 局部视图
【发布时间】:2020-06-29 16:33:44
【问题描述】:

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

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

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

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

【问题讨论】:

  • 创建一个公共代理类,其中包含您想要的模型。

标签: c# asp.net-mvc asp.net-mvc-4 model-view-controller razor


【解决方案1】:

我想知道是否可以创建一个可以有多个模型的局部视图?

是的,为这 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);
}

【讨论】:

  • 非常感谢您的回答!帮助我解决了我的问题:)。只有一件事:您的示例中的public class Descendant1 {get;set;} 可能应该是public Descendant1 desc1 {get;set;}
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-06-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-11
相关资源
最近更新 更多