I'm building websites in ASP.NET MVC and I quickly figured out that my models are getting harder to organise as they grow.What I normally do is create one model to add and edit data. But in my add view I have 2 extra properties. So I'm re-using the same model with 2 extra properties but I don't use these my edit view.Now I have a few questions regarding this.How do you organise it?Do you create one file class with multiple models in it or is it better to create a new file for each model?Is it better to create a new model if you need a few more properties?
Organising models in ASP.NET MVC
asp.net mvc
In theory, each view should have its own Viewmodel. A Viewmodel (especially with a web-based UI) is your method of representing the relevant state or input from the View. With this in mind, there would be an edit Viewmodel and a create Viewmodel.However, in practice, edit and create are nearly identical actions as far as the View is concerned. There's likely going to be very little difference between the screens (in this case, only two fields?), and they both generally represent the same object. I personally use the same Viewmodel for both views, despite a small bit of functional difference.In general, I'd say the reason the fields aren't used is relevant to whether or not you should reuse the model. Reusing a Viewmodel to represent the same general data structure in two separate places is probably fine, but reusing a class just because it happens to have the right properties with the right names is breaking the pattern.Regarding files, especially while using an IDE like Visual Studio that gives you a nice project explorer, it's best to keep one class per file. When the code is compiled, it makes absolutely no difference, so barring file system issues, this is a matter of usability and ease of programmer interaction. Also considering source control, where you might only be able to commit file-by-file, it's best not to lump more than one class together. When you change a class, you only one that one class to be considered modified, but any other classes in the file would be included.