Model *View* Controller
July 31, 2008 · 4 minute read
A lot is being made of Microsoft’s Model View Controller (or MVC) framework at the moment.
I have only spent a couple of days working with it so far but it does look promising. If you are a TDD convert or just interested in solid OOP principles such as separation of concerns it may well be right up your street.
As with all change, the emergence of this new approach to asp.net programming has caused its fair share of controversy and debate but that’s for another day. Lets just say there are those who are yet to be convinced of it’s value and those who are already sold on it.
For today though I want to focus on the View part of the equation.
Interestingly I think Scott Guthrie may have had a bit of a revelation one day when he was posting about MS AJAX on his blog. Whether MVC was already in development or not, this post does seem to lean neatly into what we’re now all talking about.
I have recently adapted the technique mentioned in that article for an AJAX web site. Lets look at some code (heavily based on Scott’s original post).
This function is pretty straightforward. Given a path to a user control and some data in the form of an object array it will attempt to render the user control and spit out an html string.
NB: To avoid tripping up asp.net we wrap our user control contents in a form prior to rendering, then remove the form afterwards.
Expose this as a method in a class (ViewManager) and you’re ready to go.
Now to an example of a view.
Note the strongly typed access to the data’s fields. This is possible due to the code-behind for this view.
I have explicitly stated the type of the data object (Customer).
You’ll also note I have used an object array rather than a single object. This just adds a bit of flexibility as you can pass in more than one object to bind the view to.
Interestingly ASP.NET MVC supports strongly typed data access using generics (example below)…
The real beauty of this templating approach though (and what Scott originally alluded to) is that you can render this html and then view it however you want. Once class I’ve used sends the rendered view out as an email.
With MS AJAX I’ve used a ModalPopup control from the ASP.NET AJAX Control Toolkit to display the html.
The similarities between this approach and MVC are fairly obvious. You can have controllers which render the view using the RenderView method and then do what you like with the resulting HTML.