ASP.NET MVC 3 - 部分vs显示模板与编辑器模板

本文探讨了在ASP.NET MVC 3中创建可重用组件的三种方式:局部视图、显示模板和编辑器模板。尽管它们在HTML呈现上相似,但在何时选择使用哪种模板时存在差异。编辑器模板适用于处理模型层次结构,自动处理集合渲染,而显示模板通常用于只读展示。局部视图则更适合视图中心的逻辑和控制器逻辑。选择使用哪种模板取决于你的应用需求和代码重用策略。
摘要由CSDN通过智能技术生成

本文翻译自: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? 是否有一个列表/文章比较这三个?


#1楼

参考:https://stackoom.com/question/L8VI/ASP-NET-MVC-部分vs显示模板与编辑器模板


#2楼

Use _partial view approach if: 在以下情况下使用_partial view方法:

  1. View Centric Logic 查看中心逻辑
  2. What to keep all _partial view related HTML in this view only. 如何仅在此视图中保留与所有_partial视图相关的HTML。 In the template method, you will have to keep some HTML outside the Template View like "Main Header or any outer border/settings. 在模板方法中,您必须在模板视图外部保留一些HTML,如“主标题或任何外边框/设置”。
  3. Want to render partial view with logic (From controller) using URL.Action("action","controller") . 想要使用URL.Action("action","controller")使用逻辑(来自控制器)渲染局部视图。

Reasons to use Template: 使用模板的原因:

  1. Want to remove ForEach(Iterator) . 想要删除ForEach(Iterator) Template is well enough to identify Model as a list type. 模板足以将Model标识为列表类型。 It will do it automatically. 它会自动完成。
  2. Model Centric Logic. 模型中心逻辑。 If multiple views are found in the same displayfor Template folder, then rendering will depend on Passed Model. 如果在Template文件夹的同一显示中找到多个视图,则渲染将取决于Passed Model。

#3楼

到目前为止还没有提到的另一个区别是,当模板执行时,partialview不会添加模型前缀这里是问题


#4楼

EditorFor vs DisplayFor is simple. EditorFor vs DisplayFor很简单。 The semantics of the methods is to generate edit/insert and display/read only views (respectively). 这些方法的语义是分别生成编辑/插入和显示/只读视图。 Use DisplayFor when displaying data (ie when you generate divs and spans that contain the model values). 在显示数据时使用DisplayFor (即,当您生成包含模型值的div和spans时)。 Use EditorFor when editing/inserting data (ie when you generate input tags inside a form). 编辑/插入数据时使用EditorFor (即在表单内生成输入标签时)。

The above methods are model-centric. 上述方法以模型为中心。 This means that they will take the model metadata into account (for example you could annotate your model class with [UIHintAttribute] or [DisplayAttribute] and this would influence which template gets chosen to generate the UI for the model. They are also usually used for data models (ie models that represent rows in a database, etc) 这意味着他们将考虑模型元数据(例如,您可以使用[UIHintAttribute][DisplayAttribute]注释您的模型类,这将影响选择哪个模板来生成模型的UI。它们通常也用于数据模型(即表示数据库中的行的模型等)

On the other hand Partial is view-centric in that you are mostly concerned with choosing the correct partial view. 另一方面, Partial是以视图为中心的,因为您最关心的是选择正确的局部视图。 The view doesn't necessarily need a model to function correctly. 视图不一定需要模型才能正常运行。 It can just have a common set of markup that gets reused throughout the site. 它可以只有一组通用的标记,可以在整个站点中重用。 Of course often times you want to affect the behavior of this partial in which case you might want to pass in an appropriate view model. 当然,您经常希望影响此部分的行为,在这种情况下,您可能希望传递适当的视图模型。

You did not ask about @Html.Action which also deserves a mention here. 你没有问过@Html.Action ,这也值得一提。 You could think of it as a more powerful version of Partial in that it executes a controller child action and then renders a view (which is usually a partial view). 您可以将其视为Partial的更强大版本,因为它执行控制器子操作然后呈现视图(通常是部分视图)。 This is important because the child action can execute additional business logic that does not belong in a partial view. 这很重要,因为子操作可以执行不属于局部视图的其他业务逻辑。 For example it could represent a shopping cart component. 例如,它可以代表购物车组件。 The reason to use it is to avoid performing the shopping cart-related work in every controller in your application. 使用它的原因是为了避免在应用程序的每个控制器中执行与购物车相关的工作。

Ultimately the choice depends on what is it that you are modelling in your application. 最终,选择取决于您在应用程序中建模的内容。 Also remember that you can mix and match. 还记得你可以混搭。 For example you could have a partial view that calls the EditorFor helper. 例如,您可以使用调用EditorFor帮助程序的局部视图。 It really depends on what your application is and how to factor it to encourage maximum code reuse while avoiding repetition. 这实际上取决于您的应用程序是什么以及如何将其考虑在内以鼓励最大程度地重用代码,同时避免重复。


#5楼

You certainly could customize DisplayFor to display an editable form. 您当然可以自定义DisplayFor以显示可编辑的表单。 But the convention is for DisplayFor to be readonly and EditorFor to be for editing. 但是惯例是DisplayForreadonlyEditorFor是用于编辑的。 Sticking with the convention will ensure that no matter what you pass into DisplayFor , it will do the same type of thing. 坚持使用约定将确保无论您传递给DisplayFor ,它都将执行相同类型的操作。


#6楼

Just to give my 2c worth, our project is using a partial view with several jQuery tabs, and each tab rendering its fields with its own partial view. 为了给我的2c值,我们的项目使用带有几个jQuery选项卡的局部视图,每个选项卡使用自己的局部视图呈现其字段。 This worked fine until we added a feature whereby some of the tabs shared some common fields. 这很好用,直到我们添加了一个功能,其中一些选项卡共享一些常见的字段。 Our first approach to this was to create another partial view with these common fields, but this got very clunky when using EditorFor and DropDownListFor to render fields and drop downs. 我们的第一个方法是使用这些常见字段创建另一个局部视图,但是当使用EditorFor和DropDownListFor来渲染字段和下拉时,这非常笨拙。 In order to get the ids and names unique we had to render the fields with a prefix depending on the parent partial view that was rendering it: 为了获得唯一的id和名称,我们必须使用前缀渲染字段,具体取决于呈现它的父部分视图:

    <div id="div-@(idPrefix)2" class="toHide-@(idPrefix)" style="display:none">
    <fieldset>
        <label for="@(idPrefix).Frequency">Frequency<span style="color: #660000;"> *</span></label>

        <input name="@(idPrefix).Frequency"
               id="@(idPrefix)_Frequency"
               style="width: 50%;"
               type="text"
               value="@(defaultTimePoint.Frequency)"
               data-bind="value: viewState.@(viewStatePrefix).RecurringTimepoints.Frequency"
               data-val="true"
               data-val-required="The Frequency field is required."
               data-val-number="The field Frequency must be a number."
               data-val-range-min="1"
               data-val-range-max="24"
               data-val-range="The field Frequency must be between 1 and 24."
               data-val-ignore="true"/>

        @Html.ValidationMessage(idPrefix + ".Frequency")

        ... etc

    </fieldset>
</div>

This got pretty ugly so we decided to use Editor Templates instead, which worked out much cleaner. 这非常难看,所以我们决定使用编辑器模板,这样做得更清晰。 We added a new View Model with the common fields, added a matching Editor Template, and rendered the fields using the Editor Template from different parent views. 我们添加了一个带有公共字段的新视图模型,添加了匹配的编辑器模板,并使用不同父视图中的编辑器模板渲染了字段。 The Editor Template correctly renders the ids and names. 编辑器模板正确呈现ID和名称。

So in short, a compelling reason for us to use Editor Templates was the need to render some common fields in multiple tabs. 简而言之,我们使用编辑器模板的一个令人信服的理由是需要在多个选项卡中呈现一些常见字段。 Partial views aren't designed for this but Editor Templates handle the scenario perfectly. 部分视图不是为此设计的,但编辑器模板可以完美地处理场景。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值