Reputation: 13511
We are doing our damnedest to NOT use RenderPartial but instead to use EditorFor and DisplayFor in 100% of cases. However, there is one scenario that we haven't been able to get to work so far: When the partial view needs the entire ViewModel, or in other words, when it needs to be Html.DisplayFor(m => m, "MyTemplateThatNeedsTheEntireViewModel")
. It works fine if it's Html.DisplayFor(m => m.Prop, "MyTemplateThatOnlyNeedsTheOneProperty")
but we can't pass the entire ViewModel in.
Is there a way to achieve this that will work both with DisplayFor
and EditorFor
?
What I see now is that either nothing (or perhaps whitespace) is rendered to my markup. However, both the compiler and ReSharper seem to think my syntax is just fine. Changing my code to call RenderPartial works perfectly, but this is what I'm trying to avoid.
I try these three lines. The RenderPartial works perfectly, the EditorFors do not work (eventual markup is an empty string or whitespace):
<% Html.EditorFor(m => m, "RetailPriceRequests/PriceRequest/PriceRequestLoadGrid"); %>
<%= Html.EditorFor(m => m, "RetailPriceRequests/PriceRequest/PriceRequestLoadGrid") %>
<% Html.RenderPartial("~/Views/Shared/EditorTemplates/RetailPriceRequests/PriceRequest/PriceRequestLoadGrid.ascx", Model); %>
Upvotes: 1
Views: 683
Reputation: 63512
If your DisplayTemplate is:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<ExampleModel>" %>
DisplayFor(m => m, "ExampleModel")
should work
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<ExamplePropertyModel>" %>
DisplayFor(m => m.ExampleProperty, "ExamplePropertyModel")
should work
One issue you could be that something is null, in which case it probably shouldn't be hitting the View at all, but you can get around this by writing:
RenderPartial("ExampleModel", Model ?? new ExampleModel());
or
RenderPartial("ExampleModel",
(Model ?? new ExampleModel() { ExampleProperty = new ExampleProperty() })
.ExampleProperty ?? new ExampleProperty());
Upvotes: 1