将整个ViewModel传递给DisplayTemplate?

时间:2010-12-08 16:06:29

标签: asp.net-mvc asp.net-mvc-2

我们最大的努力是不使用RenderPartial,而是在100%的情况下使用EditorFor和DisplayFor。但是,有一种情况我们到目前为止还无法开始工作:当部分视图需要整个ViewModel时,或者换句话说,当它需要Html.DisplayFor(m => m, "MyTemplateThatNeedsTheEntireViewModel")时。如果它是Html.DisplayFor(m => m.Prop, "MyTemplateThatOnlyNeedsTheOneProperty"),它可以正常工作但我们无法传递整个ViewModel。

有没有办法实现这一目标,这对DisplayForEditorFor都有效?

我现在看到的是,没有任何东西(或者可能是空格)呈现给我的标记。但是,编译器和ReSharper似乎都认为我的语法很好。更改我的代码以调用RenderPartial非常有效,但这正是我想要避免的。

我试试这三行。 RenderPartial工作正常,EditorFors不起作用(最终标记是空字符串或空格):

<% Html.EditorFor(m => m, "RetailPriceRequests/PriceRequest/PriceRequestLoadGrid"); %>
<%= Html.EditorFor(m => m, "RetailPriceRequests/PriceRequest/PriceRequestLoadGrid") %>
<% Html.RenderPartial("~/Views/Shared/EditorTemplates/RetailPriceRequests/PriceRequest/PriceRequestLoadGrid.ascx", Model); %>

1 个答案:

答案 0 :(得分:1)

如果你的DisplayTemplate是:

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

DisplayFor(m => m, "ExampleModel")

应该有效

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

DisplayFor(m => m.ExampleProperty, "ExamplePropertyModel")

应该有效

你可能会遇到一个问题,即某些事情是空的,在这种情况下它可能根本不应该点击View,但是你可以通过写下来解决这个问题:

RenderPartial("ExampleModel", Model ?? new ExampleModel());

RenderPartial("ExampleModel", 
    (Model ?? new ExampleModel() { ExampleProperty = new ExampleProperty() })
        .ExampleProperty ?? new ExampleProperty());