MVC2 - 如何在模板中获取父模型(容器)

Jak*_*cki 6 templates model modelmetadata asp.net-mvc-3 asp.net-mvc-2

我正在使用DataAnnotations编写MVC2应用程序.我有以下型号:

public class FooModel 
{
    [ScaffoldColumn("false")]
    public long FooId { get; set; }

    [UIHint("BarTemplate")]
    public DateTime? Bar { get; set;}
}
Run Code Online (Sandbox Code Playgroud)

我想为Bar创建一个自定义显示模板.我创建了以下模板:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<DateTime?>" %>

<div class="display-label">
    <span><%: Html.LabelForModel() %></span>
</div>
<div class="display-field">
    <span><%: Html.DisplayForModel()%></span>
    <%: Html.ActionLink("Some link", "Action", new { id = ??FooId?? }) %>
</div>
Run Code Online (Sandbox Code Playgroud)

现在,我的问题是Bar的内部模板我想从我的模型访问另一个属性.我不想为FooModel创建单独的模板,因为我将不得不对所有其他FooModel属性进行硬编码.

在使用调试器进行简短调查后,我可以看到:

  1. this.ViewData.ModelMetadata.ContainerTypeFooModel(正如预期的那样)
  2. this.ViewData.TemplateInfo有一个非公共属性VisitedObjects (类型 System.Collections.Generic.HashSet<object>),包含两个元素: FooModelDateTime?.

如何访问我的FooModel?我不想破解我使用Reflection的方法.

更新:

我已经接受了mootinator的回答,因为它认为我是允许类型安全的最佳解决方案.我也赞成了Tx3的答案,因为mootinator的答案建立在它之上.尽管如此,我认为在这种场景中应该有更好的MVC支持,我认为这在现实世界中非常普遍,但在示例应用程序中却缺少.

Kev*_*ker 0

抱歉,如果这个建议看起来很愚蠢,我还没有尝试过,但是你不能按照 Tx3 的建议去做,而不必通过定义一个泛型类来引用你想要的任何类型的父类来创建一堆新类吗?

    public class FooModel 
    {
        [ScaffoldColumn("false")]
        public long FooId { get; set; }

        [UIHint("BarTemplate")]
        public ParentedDateTime<FooModel> Bar { get; set;}

        public FooModel()
        {
            Bar = new ParentedDateTime<FooModel>(this);
        }
    }


    public class ParentedDateTime<T>
    {
        public T Parent {get; set;}
        public DateTime? Babar {get; set; }

        public ParentedDateTime(T parent)
        {
            Parent = parent;
        }

}
Run Code Online (Sandbox Code Playgroud)

您甚至可以扩展它以使用<Parent, Child>类型化泛型封装任何旧类型。

这也将为您带来强类型模板的好处

Inherits="System.Web.Mvc.ViewUserControl<ParentedDateTime<FooType>>因此,您不必在任何地方明确指定要使用的模板。这更符合事情的运作方式。