我们最大的努力是不使用RenderPartial,而是在100%的情况下使用EditorFor和DisplayFor。但是,有一种情况我们到目前为止还无法开始工作:当部分视图需要整个ViewModel时,或者换句话说,当它需要Html.DisplayFor(m => m, "MyTemplateThatNeedsTheEntireViewModel")
时。如果它是Html.DisplayFor(m => m.Prop, "MyTemplateThatOnlyNeedsTheOneProperty")
,它可以正常工作但我们无法传递整个ViewModel。
有没有办法实现这一目标,这对DisplayFor
和EditorFor
都有效?
我现在看到的是,没有任何东西(或者可能是空格)呈现给我的标记。但是,编译器和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); %>
答案 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());