views:

42

answers:

1

When I create a view and bind it directly to one class which has the properties I want to show on the view, the fields (textboxes, etc.) for it are created automatically. But when I create a ViewModel to encapsulate more than one object with data, this doesn't happen. Is there any way to get that working for a specific object which is inside the ViewModel?

Thanks.

A: 

Thanks to the commenters for teasing out the answer details.

MVC's default EditorFor "master" template, Object.ascx, has an if statement in place to prevent this from happening.

To change this behavior you need to replace the base /EditorTemplates/Object.ascx template with your own. This is a good replica of the template baked into MVC:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<% if (Model == null) { %>
    <%= ViewData.ModelMetadata.NullDisplayText %>
<% } else if (ViewData.TemplateInfo.TemplateDepth > 1) { %>
    <%= ViewData.ModelMetadata.SimpleDisplayText %>
<% } else { %>
    <table cellpadding="0" cellspacing="0" border="0">
    <% foreach (var prop in ViewData.ModelMetadata.Properties.Where(pm => pm.ShowForDisplay && !ViewData.TemplateInfo.Visited(pm))) { %>
        <% if (prop.HideSurroundingHtml) { %>
            <%= Html.Display(prop.PropertyName) %>
        <% } else { %>
            <tr>
                <td>
                    <div class="display-label" style="text-align: right;">
                        <%= prop.GetDisplayName() %>
                    </div>
                </td>
                <td>
                    <div class="display-field">
                        <%= Html.Display(prop.PropertyName) %>
                    </div>
                </td>
            </tr>  
        <% } %>
    <% }   %>
    </table>
<% } %>

This line:

<% } else if (ViewData.TemplateInfo.TemplateDepth > 1) { %>

tell the template to only go down a single level of your object graph. Simply replace the 1 with 2 or remove it entirely to change how far MVC will drill down.

More details about this template can be found here: http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-4-custom-object-templates.html

( man, I should create a macro to linking to Brad Wilson's stuff, I do it all the time ) ;)

jfar