ASP.NET MVC - Controller/Actions or Views or ViewModels first?
I'm familiar开发者_运维知识库 with the various bits of functionality of the MVC plugin to create things. For example you can create a controller, write an Action method on it, then use the "create view" function in the context menu to create a view for it.
The question is, which is it recommended to do first?
I'm thinking I might start myself a methodology like this:
- Plan out what the UI etc will look like and how it will work.
- Write unit tests for the controller actions I think I might need.
- Create Controller (maybe with default CRUD actions if it's to be that kind of controller).
- Create ViewModel class for each controller action.
- Create a strongly-typed view for each ViewModel.
- Start building the view, working back through the ViewModel to the Controller as the View is built up.
What do you think of this approach, and what do you do?
Sounds like you're on the right track. Controllers are the most easily tested component of the three. Going controller-first will make it easier to follow Test-Driven Development practices.
I've not been perfectly happy with the default view templates, but every MVC guru will point you to T4 templates, which let you roll your own. They, like the out-of-the-box view templates, will be more effective with existing view models and controllers.
I'd be tempted to define the ViewModel first, the VM(s) can consist of all or a subset of the entities required for the various Views. How you segregate your VMs would depend on your app and how you are breaking up logical units within that.
Once I had the VM(s) in a basic form I would move to Model necessary for my chosen data store (unless I had an existing data store in which case I'd have started with the Model). Then onto the controllers. You can then apply TDD with a mocked data source to verify that the VM objects returned by the controller actions match expectations. Lastly, I'd generate basic strongly typed Views (based on the ViewModel objects) for each controller action that actually resulted in UI.
Then it's play time with Jquery and CSS to make it look presentable.
精彩评论