在以前的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 回答
"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有这个说:
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等 .
'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'的文件夹中 .ViewModel / MVVM(Model-View-ViewModel)是一种架构模式,不依赖于任何框架或堆栈 .
意味着你仍然可以使用它,它只是MVC模式之上的一个额外的抽象层,它以一种形式提供数据,使其易于为视图使用 .
您可以使用dbcontext https://docs.microsoft.com/en-us/ef/core/modeling/relationships中的关系