问题
I am using EditorFor()
helper to render edit template in my view and I would like to call the DisplayFor()
inside this template to render out the Display template.
Like this
this is inside the /Shared/EditorTemplates/Client.ascx
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<BusinessNext.Models.Ef.Client>" %>
<%: Html.DisplayFor(client=>client) %>
In the DisplayFor template I render out client's properties. DisplayFor template works perfectly fine when called from everywhere else but from EditorFor template it doesn't render out anything. It seems that the DisplayFor()
call never actually gets to the DisplayFor template.
回答1:
I am afraid that the only way is to use a partial:
<%= Html.Partial("~/Views/Home/DisplayTemplates/Client.ascx", Model) %>
回答2:
It can be debatable if it is a good idea to template complicated objects, or if my approach to nested templates is a hack or not. The advantage of this is having a single template for the parent and child can both have templates rather than having to choose/use partial views.
All that aside, templated views can be nested, if you use a partial view as an go between.
The outside template will have something like below where you want to place the inner template:
Html.RenderPartial("SharedDisplayGoBetweenForFoo", item);
The shared partial would look like this:
@model Foo
@Html.DisplayFor(a => a);
The inner template would then be called and would look like any other.
来源:https://stackoverflow.com/questions/4845753/is-it-possible-to-use-displayfor-from-within-the-editorfor-template-control