What is the best ViewModel naming convention? [duplicate]
I'm writing an asp.net mvc2 project with a lot of views/partialviews. Reading on good MVC practices, I've been encourage to create ViewModels. Its really nice and makes sense to do so but I'm noticing recently that I can no longer easily remember what model is for what view. I'm hoping there is a nice naming convention f开发者_JAVA技巧or ViewModels that can handle large projects.
My question is can this situation be improved?
I like to keep it simple, for instance, if you have an object named Folder:
View = "FolderView.xaml"
ViewModel = "FolderViewModel.cs"
Make it simple:
ModelName = ViewName + "Model";
If you have model hierarchies, you sometimes need to pass the model from the view to partial views. In that case the above rule can be waived.
If you are keeping your view models in the same assembly as your views, one trick I have used to help organize views with view models in addition to a simple naming scheme like {View Name}ViewModel for the view model class is to do the following:
- Create your view class (Shell.xaml)
- In the same location, add your view model class (ShellViewModel.cs)
- Rename the view model class file to be the same name as the view, but append .model to the file path (Shell.model.cs)
- Edit the project file (either manually or using the power command extensions in VS)
- Locate the Compile element for the view model class in the project XML document
- Add a child DependentUpon element whose content is the name of the view class
- Save changes and reload the project
This will cause the view model class to be visually grouped along side the code-behind file for the view.
For ASP.NET MVC I keep my view models in a ViewModels.{Controller}
namespace and the class name is just {Action}
. I don't use the ViewModel suffix just like how the view files don't have a View suffix.
I've started going one step further and specifying if a ViewModel is used to generate a Form via EditorFor by ending the name with Form. Helps keep forms vs. simple display models easily identifiable.
精彩评论