【问题标题】:Issue with using two models in the view in ASP.NET MVC [duplicate]在 ASP.NET MVC 的视图中使用两个模型的问题 [重复]
【发布时间】:2019-01-14 23:19:00
【问题描述】:

在我看来,我正在尝试使用两个模型,但我收到一条错误消息,说只能使用一个模型。我明白了为什么只能使用一个模型但有任何解决方法,所以我可以在我的视图中使用两个模型。我已经列出了下面的代码。

控制器:

/* Parts Method */
public ActionResult Parts()
{
    return View(db.Part.ToList());
}

查看:

@model Inventory_System.Models.Transaction @model IQueryable

第一个模型用于连接到视图模型,第二个是从控制器连接到要显示的数据库列表。如何在同一个视图中同时使用这两种模型?

【问题讨论】:

  • 你需要制作一个包含这两个东西作为属性的ViewModel。你只能在一个视图中使用一个模型
  • 你需要使用ViewModel @maccettura 已经提到的。这是一个例子stackoverflow.com/a/50509915/2946329

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


【解决方案1】:

您应该创建一个具有两个属性的复合模型。

查看模型

public class CompositeModel
{
  public Transaction  Transaction {get;set}
  public List<Part> ListOfParts {get;set}   
}

控制器

 public ActionResult Parts()
{
   CompositeModel model = new CompositeModel
   {
     Transaction = new Transaction();
     ListOfParts = db.Part.ToList();
   };
   return View(model);
}

查看

@model /*Name Space*/.CompositeModel;

我认为这是一个很好的解决方案。

【讨论】:

    【解决方案2】:

    您应该创建一个包含两个模型的 ViewModel

    public class ViewModel()
    {
        public Inventory_System.Models.Transaction Transaction {get;set;}
        public IQueryable<Inventory_System.Models.Part> Part {get;set;}
    
    }
    

    【讨论】:

      猜你喜欢
      • 2018-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-19
      • 2017-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多