我可以在MVC的同一视图中使用多个viewModel吗?

Sma*_*EGA 0 .net c# asp.net-mvc viewmodel

是否可以在同一视图中使用多个视图模型?

我试图通过@model属性使用viewmodel

但是,如果我可以使用第二个viewModel,我会陷入困境,我将第二个放置在哪里?

Ciu*_*rin 5

您不能在同一视图中发送两个视图模型。

作为一种快速的解决方法,您可以创建另一个类,该类包装要在视图中发送的所有模型。这样,您将受益于强类型视图。

  public class Foo
  {
    public int ID { get; set; }
    public string Name { get; set; }
  }

  public class Bar
  {
    public int ID { get; set; }
    public string Name { get; set; }
  }

  public class FooBar
  {
    public Foo Foo { get; set; }
    public Bar Bar { get; set; }
  }
Run Code Online (Sandbox Code Playgroud)

在您的操作方法内:

  var foo = new Foo
  {
    ID = 1,
    Name = "Foo"
  };

  var bar = new Bar
  {
    ID = 2,
    Name = "Bar"
  };

  var fooBar = new FooBar
  {
    Foo = foo,
    Bar = bar
  };

  return View(fooBar);
Run Code Online (Sandbox Code Playgroud)

  • 这不是“快速解决方法”,而是ViewModels的工作方式以及可组合性和局部视图的基础 (2认同)