Shine's corner

ASP.net Webforms and the Passive View Design Pattern

This is more a personal reminder than an article.

With the release of the first bits of the ASP.Net MVC framework, I moved from webforms to the new model. But since I can't always have it my way, some times I need to use webforms. 

"If you can't beat them, join them!"

One of the biggest problems of webforms is that its isn't very testable. Implementing the MVP pattern "handles this by reducing the behavior of the UI components to the absolute minimum by using a controller that not just handles responses to user events, but also does all the updating of the view." [1].
The MVP pattern was splitted in two: The Supervising Controller and the Passive View. Today we will be talking about Passive View.

"Run Forrest, run..."

With this design pattern the view get as dumb as they can. All the logic is in the Controller. The Controller is also responsible for updating the view.

"Hello, World!"

Lets build a simple example. First we create a ASP.Net Web Application.
The objective of our application is simple: The user types his name on the text box. Pressing the Greet button and a nice little message is showed. :)
Let's define our view:

From the view we can get the typed user name and set a message.

Now, let's update our default.aspx to become our view. First we need to add a textbox, named txtUserName, a button, named btnGreetUser and a literal that will hold our greeting message (named litMessage).

Next, in the code-behind file of our default.aspx page, we add the IHomeView and implement its properties:

Notice that:

  • The page_load event of the page initializes a Presenter passing the instance of the view;
  • Our View properties map to both the textbox, for getting the name, and to the literal, for setting the message;
  • The button click handler calls a method of the Presenter.

Now that we've build the View we can't yet run the code: The Presenter is missing.

As I stated before, the Presenter will handle all te responses to user events, in this case, the button click event. So based on the needs of the view, our presenter will look like so:

Taking a closer look at the OnGreetUser() we can see that we take the user name from the view, build a simple greeting message and set back the message to the view thru the Message property of the view.

"That's all folks..."

We're done. If we run our application we can see how everything is hook up and a nice message is shown to the user when we types his name and presses the button.

Since there's a separation of the UI logic from the view implementation we can easly test our code:

 

0 comments

Leave a comment...

To Posterous, Love Metalab