Permalink
Browse files

Generate code for model properties in ASP.NET MVC List T4 templates.

  • Loading branch information...
1 parent eefdc40 commit 7e2fa745ec52053233d198283f8ab056f2bb33cd @mrward mrward committed Nov 27, 2011
Oops, something went wrong.
@@ -1,5 +1,7 @@
<#@ template language="C#" HostSpecific="true" #>
<#@ import namespace="ICSharpCode.AspNet.Mvc" #>
+<#@ import namespace="System.Collections.Generic" #>
+<#@ import namespace="System.Reflection" #>
<# if (MvcHost.IsPartialView) { #>
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<#= GetViewPageType() #>>" %>
@@ -31,15 +33,41 @@
<%: Html.ActionLink("Create", "Create") %>
</p>
<table>
- <% foreach (var item in Model) { %>
+<#
+ if (ModelHasProperties) {
+ foreach (ModelProperty modelProperty in ModelProperties) {
+#>
+ <tr>
+ <th>
+ <%: Html.LabelFor(model => model.<#= modelProperty.Name #>) %>
+ </th>
+ <th></th>
+ </tr>
+
+<#
+ }
+ }
+#>
+<% foreach (var item in Model) { %>
<tr>
+<#
+ if (ModelHasProperties) {
+ foreach (ModelProperty modelProperty in ModelProperties) {
+#>
+ <td>
+ <%: Html.DisplayFor(model => model.<#= modelProperty.Name #>) %>
+ </td>
+<#
+ }
+ }
+#>
<td>
<%: Html.ActionLink("Edit", "Edit") %> |
<%: Html.ActionLink("Details", "Details") %> |
<%: Html.ActionLink("Delete", "Delete") %>
</td>
</tr>
- <% } %>
+<% } %>
</table>
<#
if (MvcHost.IsPartialView) {
@@ -60,6 +88,11 @@
get { return (MvcTextTemplateHost)Host; }
}
+ public class ModelProperty
+ {
+ public string Name { get; set; }
+ }
+
public string GetViewPageType()
{
string viewDataTypeName = MvcHost.ViewDataTypeName;
@@ -68,4 +101,33 @@
}
return String.Empty;
}
+
+ List<ModelProperty> modelProperties;
+
+ List<ModelProperty> ModelProperties {
+ get {
+ if (modelProperties == null) {
+ modelProperties = new List<ModelProperty>(GetModelProperties());
+ }
+ return modelProperties;
+ }
+ }
+
+ bool ModelHasProperties {
+ get { return ModelProperties.Count > 0; }
+ }
+
+ public IEnumerable<ModelProperty> GetModelProperties()
+ {
+ var properties = new List<ModelProperty>();
+ foreach (PropertyInfo propertyInfo in MvcHost.GetViewDataTypeProperties()) {
+ properties.Add(CreateModelProperty(propertyInfo));
+ }
+ return properties;
+ }
+
+ ModelProperty CreateModelProperty(PropertyInfo propertyInfo)
+ {
+ return new ModelProperty() { Name = propertyInfo.Name };
+ }
#>
Oops, something went wrong.

0 comments on commit 7e2fa74

Please sign in to comment.