开发者

EF4 models and MVC models and view models ... To model or not model?

I'm currently working with EF4 and asp.net mvc 3 and I'm certainly having some trouble working through the different types of models that are possible when you bring these technologies together.

I have a database that I've defined and through EF4 I have a model of my database. But there is also the model that gets passed to my view and what about view models???

Lets say I have a mvc model of a project. This project has description, name and category properties. I have a view page that creates a project and returns it back to the controller for insertion into the database through ef4. So I initially created a class with those exact properties to be my model. However my page also requires a list of categories to choose from when creating that project, so I added a string array to my model which got passed to the page along with the other properties as part of my project model and it worked fine. Everything is great ... but I got to thinking ... because if the project model models a project then it shouldn't have a complete list of categories. It should only have the category that is part of that project.

But where does this complete list of categories go. In the view bag? This seems incorrect to me? Should I be creating a view model? How would this view model look? How about adding a method to the p开发者_开发知识库roject model that would be something along the lines of GetCategories() then I could call this method from the view page ... but does that break the separation of concerns ideal in mvc?

I'm sure many people will have different views on the subject but any commentary that will help me wade through this mess will help.

Thanks,


In all the but simplest applications you're best off not passing Model objects to Views. A View should have a ViewModel which is constructed by a Controller using data from Model objects and which contains everything that View needs to display its information.

ViewModels decouple your presentation layer from your business layer, and your example demonstrates why this is important; your View needs information about a Project, but also a complete list of all Categories that Project could belong to - such a list does not logically fit into the Project domain model object, but fits perfectly logically into a ProjectViewModel.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜