I'm a new learner of ASP.NET MVC. I looked through few books and code samples. While I learn I came up with the below question and cannot clearly understand the point below.

Most books explain that placing Models in Models folder is a Convention over Configuration. They also state that ASP.NET MVC Framework assumes developers to put Models in that folder. However, most code samples and many other developers place Models in a folder other than Models, such as ViewModels in a separate class library project (i.e. Services Project).

Is there any difference of these two ways? Is there anything ASP.NET MVC does with models if we place them in Models folder? What is good and bad about them? How do you do for your projects?

有帮助吗?

解决方案

Most books explain that placing Models in Models folder is a Convention over Configuration. They also state that ASP.NET MVC Framework assumes developers to put Models in that folder.

This is wrong. The only time asp.net-mvc uses folder structure and needs its configuration (explicitly or by convention) is when finding Views. Controllers have convention to end with suffix "Controller" and Models do not have any. You can feel free to place models where ever you like.

其他提示

You dont need to add your model(s) into the model folder that comes with the Visual Studio set up, this is only meant for basic set up. You don't even need the model(s) in the same project, you can move them into a differenct class library, which is ofen seen in larger scale applications.

However, since you are just learning MVC, then it might be worth investing your time on how to build small MVC applications, rather than how to architect them, and then concentrate on this aspect later.

Take a look at this link too, it might come in handy later on ASP.NET MVC - separating large app

A model is a kind of database representation of a domain object, it is a representation of the application model, e.g. a motorcycle... but the view that renders that motorcycle might want to display more info about the motorcycle than that which is represented by the domain object... and so in comes the View Model 'pattern' (of which there are several), which basically 'contains' the domain model...

View Model patterns usually offer flexibility, offering a kind of inheritance / obfuscation of dependency if you will.

The physical model file can indeed be placed anywhere, it is merely a class, that to be used needs to be referenced.

e.g. Domain Model

 public class Motorcycle
 {
     public string Make { get; set; }
     public string Model { get; set; }
     public int Year { get; set; }
     public string VIN { get; set; }
 }

View Model

 public class MotorcycleViewModel
 {
     public Motorcycle Motorcycle { get; set; }
     public SelectList MakeList { get; set; }
     public SelectList ModelList { get; set; }
 }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top