ASP.NET MVC 3 - 部分vs顯示模板與編輯器模板 - ASP.NET MVC 3 - Partial vs Display Template vs Editor Template

問題:

So, the title should speak for itself. 所以,標題應該說明一切。

To create re-usable components in ASP.NET MVC, we have 3 options (could be others i haven't mentioned): 要在ASP.NET MVC中創建可重用的組件,我們有3個選項(可能是其他我沒有提到的):

Partial View: 局部視圖:

@Html.Partial(Model.Foo, "SomePartial")

Custom Editor Template: 自定義編輯模板:

@Html.EditorFor(model => model.Foo)

Custom Display Template: 自定義顯示模板:

@Html.DisplayFor(model => model.Foo)

In terms of the actual View/HTML, all three implementations are identical: 就實際的View / HTML而言,所有三種實現都是相同的:

@model WebApplications.Models.FooObject

<!-- Bunch of HTML -->

So, my question is - when/how do you decide which one of the three to use? 所以,我的問題是 - 你何時/如何決定使用三者中的哪一個?

What i'm really looking for is a list of questions to ask yourself before creating one, for which the answers can be used to decide on which template to use. 我真正想要的是在創建問題之前要問自己的問題列表,其答案可用於決定使用哪個模板。

Here's the 2 things i have found better with EditorFor/DisplayFor: 以下是我使用EditorFor / DisplayFor找到的2件更好的東西:

  1. They respect model hierarchies when rendering HTML helpers (eg if you have a "Bar" object on your "Foo" model, the HTML elements for "Bar" will be rendered with "Foo.Bar.ElementName", whilst a partial will have "ElementName"). 它們在呈現HTML幫助程序時尊重模型層次結構(例如,如果在“Foo”模型上有“Bar”對象,則“Bar”的HTML元素將使用“Foo.Bar.ElementName”呈現,而部分將具有“的ElementName“)。

  2. More robust, eg if you had a List<T> of something in your ViewModel, you could use @Html.DisplayFor(model => model.CollectionOfFoo) , and MVC is smart enough to see it's a collection and render out the single display for each item (as opposed to a Partial, which would require an explicit for loop). 更強大,例如,如果你的ViewModel中有一個List<T> ,你可以使用@Html.DisplayFor(model => model.CollectionOfFoo) ,而MVC足夠聰明,可以看到它是一個集合並渲染出單個顯示對於每個項目(與Partial相反,這將需要顯式的for循環)。

I've also heard DisplayFor renders a "read-only" template, but i don't understand that - couldn't i throw a form on there? 我也聽說DisplayFor呈現了一個“只讀”模板,但我不明白 - 我不能在那裏扔一個表格嗎?

Can someone tell me some other reasons? 有人能告訴我一些其他原因嗎? Is there a list/article somewhere comparing the three? 是否有一個列表/文章比較這三個?


解決方案:

參考一: https://stackoom.com/question/L8VI
參考二: ASP.NET MVC 3 - Partial vs Display Template vs Editor Template
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章