我正在使用DataAnnotations編寫MVC2應用程序。我有以下型號:MVC2 - 如何獲取模板內的父模型(容器)
public class FooModel
{
[ScaffoldColumn("false")]
public long FooId { get; set; }
[UIHint("BarTemplate")]
public DateTime? Bar { get; set;}
}
我想爲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>
現在,我的問題是,內模板吧我想從我的模型訪問其他財產。我不想爲FooModel創建單獨的模板,因爲我不得不硬編碼所有其他FooModel屬性。
與調試簡短的調查後,我可以看到:
this.ViewData.ModelMetadata.ContainerType
是FooModel
(預期)this.ViewData.TemplateInfo
有 非公共財產 (類型System.Collections.Generic.HashSet<object>
)VisitedObjects
其中包含兩個元素:FooModel
和DateTime?
。
我該如何訪問我的FooModel?我不想破解我使用Reflection的方式。
更新:
我已經接受mootinator的答案,因爲它看起來對我來說是允許類型安全的最佳解決方案。我也提出了Tx3的答案,因爲mootinator的答案是建立在答案上的。儘管如此,我認爲在那些場景中應該有更好的MVC支持形式,我認爲這在現實世界中很常見,但在示例應用程序中卻很少見。
@Jakub:Bar.cshtml的模型是'DateTime?'的類型,沒有'm.Bar'我認爲。 – xport 2011-02-15 10:54:43
@Recycle Bin - 乾杯,編輯了這個問題。 – 2011-02-15 11:20:44
@Jakub:我不明白爲什麼你需要從'DateTime?'內訪問'FooModel'。它沒有任何意義。 :-) – xport 2011-02-15 11:25:32