Trouble 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/15
20:39 UTC
Read the original article
Hit count: 235
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:
I'd like it to be generic. So, I'd like to replace
var items = (IQueryable<TestProj.ViewModels.TestViewModel>)Model;
withvar items = (IQueryable<T>)Model;
or something to that effect.A property
Html
is automatically created for me when the view is created, but thisHtmlHelper
applies to the whole collection. I need to somehow create anitemHtml
object that applies just to the current item in theforeach
loop. I'm not sure how to do this, however, because the constructors forHtmlHelper
don't take aModel
object.
How do I solve these two problems?
© Stack Overflow or respective owner