首页 文章

ViewModel概念在ASP.NET MVC Core中是否仍然存在?

提问于
浏览
7

在以前的ASP.NET MVC版本中,您可以找到有关ViewModel的一些信息以及如何在此版本中使用它们 .

我想知道为什么我在ASP.NET Core MVC中找不到关于这个主题的任何信息?这个概念是否仍然存在,如果需要,我需要把它们放在哪里?

问题出现了,因为我想为项目制作仪表板 . 项目是我的网络应用程序的主要入口点 . 他们有许多关系,例如里程碑 .

楷模:

public class Project
{
    public int ProjectId { get; set; }
    public string Name { get; set; }

    public ICollection<Milestone> Milestones { get; set; }
    ...
}

public class Milestone
{
    public int MilestoneId { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public DateTime Deadline { get; set; }
    public int? ParentId { get; set; }
    public Milestone Parent { get; set; }

    public ICollection<Milestone> Childrens { get; set; }
    ...
}

在ASP.NET Core之前,我创建了一个ProjectDashboardViewModel,用于获取视图的信息 . 我可以使用相同的方法吗?

3 回答

  • 17

    "Does the concept still exist?" "Can I use the same approach?"

    是的,ViewModel概念仍适用于.NET Core,您仍然可以像以前一样使用它们,即将选择的数据组合成符合特定视图需求的“形状” .

    "I can't find any information about this topic in ASP.NET Core MVC"

    官方文档广泛讨论了视图模型 . The Overview of ASP.NET Core MVC section有这个说:

    模型职责MVC应用程序中的模型表示应用程序的状态以及应由其执行的任何业务逻辑或操作 . 业务逻辑应该封装在模型中,以及用于持久化应用程序状态的任何实现逻辑 . 强类型视图通常使用专门设计的ViewModel类型来包含要在该视图上显示的数据;控制器将从模型中创建并填充这些ViewModel实例 .

    In the Rendering HTML with views section

    您可以使用多种机制将数据传递给视图 . 最强大的方法是在视图中指定模型类型(通常称为视图模型,以区别于业务域模型类型),然后将此类型的实例传递给操作中的视图 . 我们建议您使用模型或视图模型将数据传递到视图 .

    The MVC/Advanced/Application Parts section还讨论了视图模型,the sample code there显示了如何将多个不同的对象组合在一起供视图模型使用 .

    他们还提到了他们in the section on Partial Views . 有一些示例代码与here一起使用,但这些示例实际上并没有真正突出模型和视图模型之间的区别 .

    通过以下文档搜索也会突出显示一些内容:https://docs.microsoft.com/en-us/search/index?search=viewmodel&scope=ASP.NET+Core

    "..i want to make a dashboard for projects"

    在您的情况下,您要显示的所有数据的数据然后您可能不需要视图模型,因为它只是您的 Project 模型的镜像 .

    但是,如果要在项目仪表板上显示其他信息,例如一些数据汇总了有关正在进行的项目数量的数据,一个项目落后的项目列表等,然后您可以组装一个具有以下属性的视图模型:Project,NumberInProgressPrjects,OverdueProjectsList等 .

    public class ProjectDashboardViewModel
    {
        public Project Project { get; set; }
        public int NumberInProgressProjects { get; set; }
        public ICollection<OverdueProjectInfo> OverdueProjectsList { get; set; }
    }
    

    's just an example, the point is you can use the view model to encapsulate all of the data needed by your view, rather than your controller returning a model object that matches a single domain object (often a table from your database) and then lots of additional data that'需要在 ViewData 集合中使页面的其余部分起作用(例如填充下拉列表所需的数据) . 有很多关于视图模型的优秀文章,例如this previous question covers them exhaustively,并且在.NET MVC Core中与其他版本的MVC一样重要 .

    "..where i need to put them?"

    您可以将它们放在您选择的位置,只需确保在需要时使用 using 语句 . 较小项目中的典型约定是将它们放在名为'ViewModels'的文件夹中 .

  • 3

    ViewModel / MVVM(Model-View-ViewModel)是一种架构模式,不依赖于任何框架或堆栈 .

    意味着你仍然可以使用它,它只是MVC模式之上的一个额外的抽象层,它以一种形式提供数据,使其易于为视图使用 .

  • -1

相关问题