Most MVC tutorials I’ve been reading seem to create 4 View objects for each Model. For example, if my Model is “Foo”, there seem to be 4 .cshtml files: Foo/Create, Foo/Delete, Foo/Details, and Foo/Edit. Using the VisualStudio “scaffolding” helper does this as well.
Is this really considered MVC best-practice? It just feels wrong to have 4 classes that are 80-90% identical to each other. When I add a new field to Foo, I need to edit all 4 .cshtml files. This sort of dual-maintenance (quad-maintenance?) just makes my OO skin crawl.
Please tell me: is there an expected/accepted best-practice which handles this differently? Or, if this really IS accepted best-practice, tell me why the quad-maintance shouldn’t make me squirm.
I’m a reasonably skilled veteran of ASP.NET / c# / OO Design, but pretty new to MVC; so apologies if this is a noob question. Thanks in advance for your help!
Edit: thanks for all the replies! I marked the most thorough one as the answer, but upvoted all that were helpful.
You’ll probably need between two and four different views:
Thus, if your model doesn’t have too many properties to show them all in a table, and if you’re OK with not having a static, non-editable view for just examining, you can get well away with just List and Edit, and scrap the other two.
However, this doesn’t solve your problem of double (or triple) maintenance if you update your model. There’s other magic for that 😉
In ASP.NET MVC 3, there are extensions on
HtmlHelperthat let you doHtml.DisplayForModel()andHtml.EditorForModel(). These use predefined templates to nest themselves into your object and draw up display/edit fields for all public properites. If you passDisplayForModelanIEnumerable<Foo>, it will create a table with column headers that are the property names ofFoo(using theDisplayNameattribute information if you supplied it) and where each row represent oneFooinstance. If you giveEditorForModelaFoo, it will create a<label>and an<input>for each public property onFoo.All of the templates used by these powerful extension methods can be replaced by you, if you’re not happy with the defaults. This can be done either on the level of
Foo, in which case you’d be back in your double-maintenance scenario, or on lower levels (such asstringorDateTime) to affect all editor/display fields generated with the templates.For more information on exactly how this works, google “ASP.NET MVC 3 editor templates” and read a couple of tutorials. They’ll explain the details much better than I could.