Struggling with ASP.NET MVC auto-scaffolder template

Posted by DanM on Stack Overflow See other posts from Stack Overflow or by DanM
Published on 2010-03-14T20:45:53Z Indexed on 2010/03/16 19:11 UTC
Read the original article Hit count: 282

I'm trying to write an auto-scaffolder template for Index views. I'd like to be able to pass in a collection of models or view-models (e.g., IQueryable<MyViewModel>) and get back an HTML table that uses the DisplayName attribute for the headings (th elements) and Html.Display(propertyName) for the cells (td elements). Each row should correspond to one item in the collection.

Here's what I have so far:


<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>

<%
    var items = (IQueryable<TestProj.ViewModels.TestViewModel>)Model;
        // How do I make this generic?
    var properties = items.First().GetMetadata().Properties
        .Where(pm => pm.ShowForDisplay && !ViewData.TemplateInfo.Visited(pm));
%>
    <table>
        <tr>
<%
            foreach(var property in properties)
            {
%>
                <th>
                    <%= property.DisplayName %>
                </th>
<%
            }
%>
        </tr>
<%
        foreach(var item in items)
        {
            HtmlHelper itemHtml = ????;
                // What should I put in place of "????"?
%>
            <tr>
<%
                foreach(var property in properties)
                {
%>
                    <td>
                        <%= itemHtml.Display(property.DisplayName) %>
                    </td>
<%          
                }
%>
            </tr>
<%
        }
%>
    </table>

Two problems with this:

  1. I'd like it to be generic. So, I'd like to replace var items = (IQueryable<TestProj.ViewModels.TestViewModel>)Model; with var items = (IQueryable<T>)Model; or something to that effect.

  2. A property Html is automatically created for me when the view is created, but this HtmlHelper applies to the whole collection. I need to somehow create an itemHtml object that applies just to the current item in the foreach loop. I'm not sure how to do this, however, because the constructors for HtmlHelper don't take a Model object.

How do I solve these two problems?

© Stack Overflow or respective owner

Related posts about asp.net-mvc

Related posts about asp.net-mvc2