同一视图中的多个模型?

时间:2014-06-11 23:05:06

标签: c# asp.net-mvc entity-framework

我对MVC相对较新,我正在尝试以代码优先的方式为用户填写并提交一页的表单。我目前在Domain文件夹中有一些模型类,但需要有一个视图来为用户一次显示每个模型的所有属性。

除此之外,我还试图让模型与彼此合作。例如,其中一个模型类包含以下内容:

namespace HROnboarding.Domain
{
    public class SoftwareNeeded
    {
        //Primitive Properties
        public int Id { get; set; }
        public string SoftwareName { get; set; } //piece of software (GIMP, VS13, etc)
        public bool isNeeded { get; set; } //whether or not it is needed by the user
    }
}

但是,如果用户选择根本不需要计算机,则不需要这样做。此属性保存在下面显示的模型中:

namespace HROnboarding.Domain
{
    public class Employee
    {
        public int ID { get; set; }

        [DisplayName("First Name")]
        public string FirstName { get; set; }
        [DisplayName("Last Name")]
        public string LastName { get; set; }
        public string Department { get; set; }
        public string Position { get; set; }
        public bool NeedsPhone { get; set; }
        public bool NeedsComputer { get; set; }
        public bool NeedsCredit { get; set; }
    }
}

目前,我已经制作了MVC"开箱即用"仅限Employee的HomeController和相关视图,因此它显示了可用于更改为用户并提交的上述属性。

对于每个模型,我在另一个文件夹中也有一个DbContext,这样就可以生成数据并将其连接到本地SQL数据库。

我如何才能将SoftwareNeeded类显示在同一页面上,以便它可以同时使用?

我的猜测是,我需要以某种方式创建一个通用视图文件,以封装来自两个类的数据,并将其显示给用户。我的第一直觉是将所有模型类数据放入一个表中,以便它可以一次填写并作为一个整体提交。

我显然不太确定从哪里开始,或者我是否正确接近问题。

非常感谢任何帮助,谢谢。

1 个答案:

答案 0 :(得分:7)

处理这种方法的一种方法是使用ViewModel,它将由视图所需的模型类型组成。

例如:

public class OnBoardEmployeeViewModel
{
   public Employee Employee { get; set; }
   public SoftwareNeeded SoftwareNeeded { get; set; }
}

另一种选择是仅构建ViewModel中的视图中显示的字段,然后在提交时构造Model类的实例。

进一步阅读MVC中的视图模型:http://sampathloku.blogspot.com/2012/10/how-to-use-viewmodel-with-aspnet-mvc.html