简体   繁体   English

在MVC中将ViewModel类放在哪里

[英]Where to put ViewModel classes in MVC

My question is very simple. 我的问题很简单。 I want to know where to put my ViewModels in an MVC application. 我想知道将ViewModels放在MVC应用程序中的位置。

Currently the project I'm working on only has ViewModels and they are stored in the Models folder. 目前,我正在处理的项目只有ViewModels ,它们存储在Models文件夹中。 In that folder we directly create ViewModel classes. 在该文件夹中,我们直接创建ViewModel类。

But normally I would also have Model classes, to get data from a database or something. 但是通常我还会有Model类,以便从数据库或其他东西获取数据。 Then from a Controller I'd 'talk' to a Model method and store the result in a ViewModel property. 然后,从Controller我将与模型方法“对话”,并将结果存储在ViewModel属性中。

But where do I put the Model classes and ViewModel classes when I use both of them? 但是,当我同时使用Model类和ViewModel类时,该将它们放在哪里? What is a good practice in the sense of structuring my files/folders for these two? 从这两个方面来构造我的文件/文件夹的意义上,什么是最佳实践?

Just create a new folder called ViewModels inside your project. 只需在项目内部创建一个名为ViewModels的新文件夹。 So that along with the Views, Controllers and Models folders, you'll also have ViewModels. 这样一来,除了Views,Controllers和Models文件夹外,您还将拥有ViewModels。 Like you already said, you talk to your DAL using your models and you talk to your views using your view models. 就像您已经说过的那样,您使用模型与DAL对话,并使用视图模型与视图对话。

You need to structure your files and folders in a way that you and the people that follow you will find intuitive and maintainable. 您需要以一种使您和跟随您的人都能直观且易于维护的方式来构造文件和文件夹。

I don't think there is any hard and fast rules about folder structure, just some are a lot worse than others. 我认为关于文件夹结构没有硬性规定,只是有些规定比其他规定差很多。 If it seems illogical and a bit smelly, then it probably is. 如果看起来不合逻辑且有点难闻,则可能是。

What you're proposing seems fine 你的建议似乎很好

创建单独的文件夹“ ViewModels”,并在控制器中引用名称空间,并在各自的视图中引用相同的名称空间

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM