开发者

View strongly-typed with ViewModel doesn't generate fields automatically

开发者 https://www.devze.com 2023-01-09 00:15 出处:网络
When I create a view开发者_如何学Python 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

When I create a view开发者_如何学Python 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.


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 ) ;)

0

精彩评论

暂无评论...
验证码 换一张
取 消