【问题标题】:Why not use Html.EditorForModel()为什么不使用 Html.EditorForModel()
【发布时间】:2011-06-30 15:26:52
【问题描述】:

好的,我刚刚发现了 MVC 中的 EditorForModel,我想知道什么时候应该在我的每个属性上使用它而不是 EditorFor?为什么当我添加一个强类型视图时它不使用它并在每个属性上构建一个EditorFor

我迟到了...但感谢您提供的信息!

【问题讨论】:

标签: c# asp.net-mvc-3 html-helper


【解决方案1】:

由于接受的答案是仅链接的答案(并且已被删除),我想我实际上会回答来自Brad Wilson 的博客:ASP.NET MVC 2 Templates, Part 1: Introduction 的问题。

模型表达式是对当前模型进行操作的简单助手。行 DisplayForModel() 等价于 DisplayFor(model => model)。

TL;DR 对于EditorFor(model => model)EditorForModel() 可以假设相同的想法;这些辅助方法实现了同样的目的。 EditorForModel() 假定模型表达式是传递给视图的 @model

以以下模型和视图为例:

public class Person
{
    public string Name {get; set;}
    public Address MailingAddress {get; set;}
}

public class Address
{
    public String Street {get; set;}
    public String City {get; set;}
    public String State {get; set;}
}

Create.cshtml:

@model MyNamespace.Models.Person

/* So, you need an Editor for the Person model? */
@Html.EditorForModel()
/*the above is equivalent to @Html.EditorFor(model => model) */

/* you need to specify the Address property that the editor accepts? */
@Html.EditorFor(model => model.MailingAddress)

【讨论】:

    【解决方案2】:

    您应该尽可能使用它,但有时您需要可自定义各个 Html.EditorFor 使用。

    至于为什么内置模板不使用它,这主要是因为它们总体上很傻,而且如果我记得,它们还需要在每个 @987654322 周围包装元素(如表格行等) @。

    【讨论】:

      【解决方案3】:

      @Html.EditorForModel() ??并放弃写自己观点的乐趣? 微笑

      除了乐趣之外,将这样做作为一种习惯是相当冒险的。考虑以下常见场景 - 您的客户表中的数据库中有一个布尔变量 IsMale。很明显,您不想要默认版本(带有复选框的 IsMale) - 您可能想要更友好的东西,比如 {select, Options .... , /select} 标签,对吧?这就是视图真正开始发挥作用的地方。这就是定制。每个观点都有点不同。您拥有 RAZOR 引擎,将其发挥到极致!在您看来,您可以覆盖任何内容,甚至可以手动键入您自己的一整段 HTML 代码。

      【讨论】:

      • EditorForModel() (不带参数)将根据约定查找自定义 EditorTemplates。该功能与使用的什么模板无关。
      猜你喜欢
      • 2016-08-23
      • 1970-01-01
      • 1970-01-01
      • 2013-07-19
      • 1970-01-01
      • 2019-06-17
      • 1970-01-01
      • 1970-01-01
      • 2014-08-26
      相关资源
      最近更新 更多