Building a template to auto-scaffold Index views in ASP.NET MVC
        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/15
            0:29 UTC
        
        
        Read the original article
        Hit count: 813
        
I'm trying to write an auto-scaffolder 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;
        // Should be 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)
        {
%>
            <tr>
<%
                foreach(var property in properties)
                {
%>
                    <td>
                        <%= Html.Display(property.DisplayName) %>
                            // This doesn't work!
                    </td>
<%          
                }
%>
            </tr>
<%
        }
%>
    </table>
Two problems with this:
- 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.
- The - <td>elements are not working because the- Htmlin- <%= Html.Display(property.DisplayName) %>contains the model for the view, which is a collection of items, not the item itself. Somehow, I need to obtain an- HtmlHelperobject whose- Modelproperty is the current- item, but I'm not sure how to do that.
How do I solve these two problems?
© Stack Overflow or respective owner