The first release of Asp.Net MVC lacks an implementation of the DataList, so I’ve created a simple extension to the framework that provides basic DataList support.

I’ve based the DataList off of the excellent Grid extension found in the MvcContrib project.

Get the project files Here

Getting Started

In order to use the DataList extension you’ll need to reference an assembly that contains the DataList code, and add the correct namespace to the web.config.

In my sample solution, I’ve created a single project that contains the DataList code inside of an Asp.Net MVC Web project:

image

I reference the namespace in my Views/web.config:

<namespaces>
  <add namespace="DataListExtension.UI"/>
</namespaces>

Using the DataList

Once you’ve included the DataList into your project and setup the namespace, you’ll have a new extension method available in the HtmlHelper instance in your views.

The DataList uses the same pattern the MvcContrib Grid for constructing the actual DataList.  The HtmlHelper extension method returns an instance of the DataList<>, as do all the member functions in the DataList<> class.  This allows you to ‘chain’ calls to the DataList and configure it through the front-end code:

<% Html.DataList(Model.TestValues).Columns(3).Item(item =>
    {
        item.Template( dataItem => {
        %>
            <div style="border: solid 1px green;">
                This is number: 
                <span style="font-weight: bold;"><%= dataItem %></span>
            </div>  
        <%        
        });
    }).Render(); %>

What this code is doing is creating a DataList around the TestValues property of the model, settings the number of columns to 3, and then specifying the template to use for each item rendered:

image 

The call to render is required when using the <% %> syntax, and it will write directly to the current response buffer. Optionally, you can use the <%= %> syntax,  which will return a string ( which will eventually be rendered to the current response buffer ).

Along with using templates, you can also optionally use a partial view by calling item.PartialView(…).

Future Enhancements

The current version works for its initial intent of displaying vertically expanding list of items, however there’s an almost limitless amount of possible enhancements that can be added.  Some of the features I’ll be adding in the future include:

  • Paging
  • Adding the ability to pass attributes to the parent container
  • Adding Horizontal Repeating
  • Custom Renders to better control the HTML output

- Colin