asp.net MVC DisplayTemplates 和 EditorTemplate 命名约定 [英] asp.net MVC DisplayTemplates and EditorTemplate naming convention
问题描述
我有几个关于 MVC 2 中 DisplayTemplates 和 EditorTemplates 的命名约定的问题.
I've got a couple of questions about the naming convention for the DisplayTemplates and EditorTemplates in MVC 2.
例如,如果我有一个带有子帐户列表的客户对象,我该怎么做:
If for example I have a customer object with a child list of account how do I:
为账户列表创建一个显示模板,文件名是什么?
Create a display template for the list of accounts, what is the file called?
当我在执行 foreach( var c in Model.Accounts )
时,我如何在 foreach 循环中调用显示寺庙?当我在 foreach 中执行 Html.DisplayFor( x => x )
时,x
是模型,而不是在这种情况下 c
.
When I'm doing a foreach( var c in Model.Accounts )
how do I call a display temple while in the foreach loop? When I do Html.DisplayFor( x => x )
inside the foreach x
is the model and not in this case c
.
提前致谢.
推荐答案
是的,这是我最喜欢的功能之一,但它在某些方面有点令人困惑.
Yeah, this is one of my favorite features, but it's a bit confusing for some things.
因此,为任何类创建模板,名称基于类型的 Name 属性,例如,如果您在视图中执行 <%= model.GetType().Name %> ,您可以看到什么我是说.例如,如果您的帐户列表是 IList,则对该类型的 .Name 的调用将返回 List`1
.这是一个合法的文件名,因此如果您将 List`1.ascx
放在 DisplayTemplates 文件夹中,它会找到并使用它.据我所知,它不会遍历类层次结构,例如,如果您将 IEnumerable`1.ascx 文件放在那里,它不会找到它.
So, creating a template for any class, the name is based on the type's Name property, so for example if you do a <%= model.GetType().Name %> in your view, you can see what I mean. As an example, if your list of accounts is an IList, then the call to .Name on the type would return List`1
. That's a legal file name, so if you put List`1.ascx
in your DisplayTemplates folder, it'll find it and use it. from what I can tell, it won't traverse the class hierarchy, though, so for example if you put an IEnumerable`1.ascx file in there, it won't find it.
要在循环中显示,您需要将 item 变量传入 lambda,因此在您的示例中:
To display in a loop, you need to pass in the item variable into the lambda, so in your example:
<% foreach (var c in Accounts){ %>
<li><%= Html.DisplayFor(x => c) %></li>
<%}%>
希望有所帮助.保罗
这篇关于asp.net MVC DisplayTemplates 和 EditorTemplate 命名约定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!