In Part 1 of this series, we created an e-commerce site that
implemented basic product listing/browsing support. We implemented this
site using the ASP.NET MVC Framework, which led us to naturally structure the
code into distinct controller, model and view components.
When a browser sends a HTTP request to our web site, the
ASP.NET MVC Framework will use its URL routing engine to map the incoming request to an action
method on a controller class to process it. Controllers in a MVC based
application are responsible for processing incoming requests, handling user
input and interactions, and executing application logic based on them
(retrieving and updating model data stored in a database, etc).
When it comes time to render an HTML response back to the
client, controllers typically work with "view" components - which are
implemented as separate classes/templates from the controllers, and are
intended to be focused entirely on encapsulating presentation logic.
Views should not contain any application logic or database
retrieval code, instead all application/data logic should only be handled by
the controller class. The motivation behind this partitioning is to help
enforce a clear separation of your application/data logic from your UI
generation code. This makes it easier to unit test your application/data
logic in isolation from your UI rendering logic.
Views should only render their output using the
view-specific data passed to it by the Controller class. In the ASP.NET
MVC Framework we call this view-specific data "ViewData". The
rest of this blog post is going to cover some of the different approaches you
can use to pass this "ViewData" from the Controller to the View to