为什么不使用Html.EditorForModel()

Vin*_*nyG 27 c# html-helper asp.net-mvc-3

好的,我刚刚发现了关于EditorForModelMVC的内容,我想知道何时应该使用它来代替EditorFor我的每个属性?为什么当我添加强类型视图时,它不使用它并EditorFor在每个属性上构建一个?

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

Car*_*all 23

由于接受的答案是一个仅链接的答案(并被删除),我想我实际上回答了从Brad Wilson的博客中获得的问题:ASP.NET MVC 2模板,第1部分:简介.

模型表达式是在当前模型上运行的简单助手.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;}
}
Run Code Online (Sandbox Code Playgroud)

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)
Run Code Online (Sandbox Code Playgroud)


Dom*_*nic 3

您应该尽可能使用它,但有时您需要个性化Html.EditorFor使用的可定制性。

至于为什么内置模板不使用它,主要是因为它们通常很愚蠢,而且还因为,如果我记得的话,它们需要将元素(如表格行等)包裹在每个Html.EditorFor.