Displaying complex types in ASP.NET MVC3 RC2

2019-05-07 13:46发布

I have a model that uses a complex type as a property.

namespace Web.Models {
    public class Business : IModel {
        [Key, HiddenInput(DisplayValue = false)]
        public Guid ID { get; set; }

        public Position Position { get; set; }

        public bool Active { get; set; }

        public ICollection<Comment> Comments { get; set; }

        public Business() {
            ID = Guid.NewGuid();
            Position = new Position();
        }
    }

    public class Position {
        public double Latitude { get; set; }
        public double Longitude { get; set; }
    }
}

When I came to create a form of the Business model, the Position property wasn't displayed. I'm sure complex types were displayed by default in MVC2. Assuming that this might be a switch in MVC3 I tried the following steps to no avail:

  1. Decorated the Position property with the ScaffoldColumn(true) attribute.
  2. Created a Position.cshtml view in Views\Shared\EditorTemplates.

My current workaround has been to convert my custom Object.ascx from MVC2 to an MVC3 Razor Object.cshtml. My hesitation is that I'm positive my custom Object.ascx was based on the original as blogged by Brad Wilson.

@if (ViewData.TemplateInfo.TemplateDepth > 1) {
    @ViewData.ModelMetadata.SimpleDisplayText
}
else {
    <div class="editor">
        @foreach (var prop in ViewData.ModelMetadata.Properties.Where(pm => pm.ShowForEdit && !ViewData.TemplateInfo.Visited(pm))) {
      if (prop.HideSurroundingHtml) {
            @Html.Editor(prop.PropertyName)
      }
      else {
            <div class="field">
                @(prop.IsRequired ? "*" : "")
                @Html.Label(prop.PropertyName)
                @Html.Editor(prop.PropertyName)
                @Html.ValidationMessage(prop.PropertyName)
            </div>
      }
  }
    </div>
}

So questions are:

  1. Has the default behaviour changed or am I missing something?
  2. Is there a better way to switch on the visibility of complex types?
  3. Is it possible to access the default templates in ASP.NET MVC3?

Rich

1条回答
闹够了就滚
2楼-- · 2019-05-07 14:00

The default Object.ascx template will only display one level of an object graph.

There is a line on top that checkes to see if the depth is > 1 and then bails on rendering.

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

Change to:

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

Or remove that if entirely.

查看更多
登录 后发表回答