Developer's Perception

Odd thoughts from a developer.

Maintainable ASP.NET Webforms - Part II

| Comments

In the last post I described how I believe that implementing the MVP pattern is a feasible way of improving ASP.NET Web Forms code: part 1

The most important lesson is still that you should not use ASP.NET Web Forms unless you absolutely have to.

The Example

I have added a tiny example to github: example

Like any contrived example it might be too simple and too silly to really show the power of implementing the pages this way, but here is a short walk-through of the flow anyways:

The view loads the presenter with a reference to itself and asks it to PresentAllDogs:

1
2
3
4
5
protected void Page_Load(object sender, EventArgs e)
{
  presenter = new DogSearchPresenter(this);
  presenter.PresentAllDogs();
}

The presenter then retrieves all the dogs (probably from some kind of data layer) and asks the view to render the dogs:

1
2
3
4
public void PresentAllDogs()
{
  view.RenderDogs(Dog.All());
}

The view just assigns a local field with the values retrived (in some scenarios it might be doing a databind or similar, all depending on how the template aspx is used):

1
2
3
4
public void RenderDogs(IList<Dog> dogs)
{
  Dogs = dogs;
}

When the template is rendered it automatically renders the Dogs from the view:

1
2
3
4
5
6
7
8
9
10
<table>
  <tr>
      <th>Name</th><th>Race</th>
  </tr>
  <%foreach(var dog in Dogs) { %>
  <tr>
      <td><%=dog.Name%></td>   <td><%=dog.Race%></td>
  </tr>
  <% } %>
</table>

This way of rendering is my preferred as it puts just the right amount of rendering logic in the template. It does not work well if you need to manipulate specific rows of the table and have the viewstate handle which you clicked.

For this you could use the listview control which is a decent compromise between using raw template rendering and having the view set values on elements using the runat server tag (I definetely prefer the first template rendering.)

Happy coding!

Comments

Alexander Beletsky

Good stuff.

There is ASP.NET MVP framework.

http://aspnetmvp.codeplex.com/

But I also still prefer lightweight custom solutions.

Comments