Differences between Html.TextboxFor and Html.EditorFor in MVC and Razor
为什么默认情况下在添加新的"编辑"视图时更改了这些设置? 使用
我找到了这个
By default, the Create and Edit scaffolds now use the Html.EditorFor helper instead of the Html.TextBoxFor helper. This improves support for metadata on the model in the form of
data annotation attributes when the Add View dialog box generates a view.
TextBoxFor:它将像指定输入表达式的文本输入html元素一样呈现。用简单的话来说,它将始终像输入文本框一样呈现,而不管与控件绑定的属性的数据类型如何。
EditorFor:此控件有点聪明。它根据属性的数据类型呈现HTML标记。例如。假设模型中有一个布尔属性。为了在视图中将此属性显示为复选框,我们可以使用CheckBoxFor或EditorFor。两者将生成相同的标记。
使用EditorFor有什么好处?
众所周知,根据属性的数据类型,它会生成html标记。因此,假设明天如果我们更改模型中属性的数据类型,则无需更改视图中的任何内容。 EditorFor控件将自动更改html标记。
在EditorFor查看类型和元信息时,可以呈现您提供的另一个控件或模板。
例如,对于DateTime属性,您可以创建使用jQuery DatePicker的模板。
这是先前评论中未提及的基本区别之一:
1 | @Html.TextBoxFor(model => model.DateSoldOn, new { @readonly ="readonly" }) |
上面的代码可以正常工作,与下面的代码一样,您无法将其控制为只读。
1 | @Html.EditorFor(model => model.DateSoldOn, new { @readonly ="readonly" }) |
字符串数据类型的html输出也略有不同。
1 2 3 4 5 | Html.EditorFor: <input id="Contact_FirstName" class="text-box single-line" type="text" value="Greg" name="Contact.FirstName"> Html.TextBoxFor: <input id="Contact_FirstName" type="text" value="Greg" name="Contact.FirstName"> |