My First Five Months with ASP.Net MVC – NxtGenUG
At OCC we have been using Microsoft's web application framework ASP.Net MVC on a number of our projects and products for a couple of years now and really enjoy the flexibility, power and transparency it offers. But it's still relatively young and new features are added frequently so we're keen to learn as much as we can from others that have been working with it.
With that in mind, last week James and I attended a NxtGenUG meeting with a talk from Richard Costall covering useful tips and tricks for those using ASP.NET MVC 3.0, based on his first five months of working with it on a new project. Richard demonstrated a simple site created using the new Razor view engine.
His main points were:
- Creating a ViewModel for each View is generally good practice. This allows data of relevance to the View only (e.g. page title) to be decoupled from core entity data.
@Html.EditorFor()is passed a collection, it will render an editor view for each member of the collection automatically – no need to write looping code.
- Mixed collections of inherited entities (for example, a shopping basket containing different sorts of product) are very easy to display and edit using MVC. Just create a View to display each inherited type. The MVC plumbing will automatically work out which View to use based on the type of each object in the collection. Ensuring that the correct ViewModel is bound on processing of posted data is a little trickier – if necessary, you can override the default ModelBinder implementation.
- The Post-Redirect-Get pattern can save writing a lot of ViewModel rebuild code when submitted data is rejected due to a validation failure. Add the
ModelStateToTempDataattribute (from MvcContrib) to the
HttpGetaction to override the default ViewModel data with the user's previous inputs. This pattern also avoids the "resend previously submitted information" warning displayed by the browser when F5 is pressed after a POST.
- Use Html Extension Helpers to implement non-standard editor controls such as sliders.
There was some lively discussion in the group concerning the relative merits of MVC and WebForms technologies for commercial development. The general view was that MVC was the better technology to use – it produces elegant and compact HTML (no nasty viewstates), plays well with jQuery, enables finer control of rendering and is more easily testable and reusable. However, some thought the lack of rapid prototyping support may make it a hard sell in time-pressed commercial environments; perhaps there is room for some innovation there.
Thanks to NxtGenUG and Richard for an interesting and informative evening!