Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
446 views
in Technique[技术] by (71.8m points)

model view controller - asp.net MVC DisplayTemplates and EditorTemplate naming convention

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?

  • 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.

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yeah, this is one of my favorite features, but it's a bit confusing for some things.

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.

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>
<%}%>

Hope that helps. Paul


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...