views:

107

answers:

2

I am dynamically generating a table to present some tabular data. Normally I would not go near tables, but for this kind of data it is appropriate.

I am noticing my view code is becoming very spaghetti like. Assigning classes on cells and rows in the body of loops is starting to look just awful (bad flashbacks to my asp 3.0 days).

I looked into using the runtime serialization to json for my DTOs and then using a JQuery plugin for templated rendering of JSON. It seems like a "cool" idea, but is more of a programming exercise than I care to do at the moment.

How are people building more involved UIs with asp.net mvc?

A: 

I've written some HtmlHelper extensions to help with table building. These extensions use a TagBuilder in code to generate the rows according to the values and HTMl attributes defined. The view code is considerably cleaner using these extension methods and the extension methods themselves are testable to ensure that they produce clean code reliably.

Sample view code:

<% var alternating = false;
   foreach (var model in Model) { %>
   <% using (Html.BeginTableRow( new { @class = alternating ? "alternating-row" : "" } )) { %>
       <%= Html.TableElement( model.Column1 ) %>
       <%= Html.TableElement( model.Column2, new { @class = 'some-class' } ); %>
       <%= Html.TableElement( model.Column3 ) %>
   <% }
      alternating = !alternating;
    %>
<% } %>

In addition, I've actually create a grid control that will generate a styled table using the above and most of my view code consists of rendering the grid control with the proper model.

 <% Html.RenderPartial( "GridControl", Model, ViewData ); %>
tvanfosson
+1  A: 

If you're concerned about how your view markup mixed with code looks, you can try an alternate view engine:

All of these view engines take different approaches to combining code and markup that can make your view markup "cleaner".

Sean Carpenter
Thanks for the links. It looks like NVelocity and NHaml are template replacement engines. The functionality looks like something that can be handled with jQuery and jTemplates. Spark looks interesting in that it defines language constructs to do processing and logically control what is rendered.
blu
A big differences between NVelocity/NHaml and jTemplates: They are server-side engines so can call .Net code as part of rendering and don't add any overhead at the client side.
Sean Carpenter