Editor() HTML Helper 方法用于简单类型视图,EditorFor() HTML Helper 方法用于强类型视图,根据模型对象属性的数据类型生成 HTML 元素。
Html.Editor的定义:
// Summary:
// Returns HTML markup for the expression, using an editor template. The template
// is found using the expression's Microsoft.AspNetCore.Mvc.ModelBinding.ModelMetadata.
//
// Parameters:
// htmlHelper:
// The Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper instance this method extends.
//
// expression:
// Expression name, relative to the current model. May identify a single property
// or an System.Object that contains the properties to edit.
//
// Returns:
// A new Microsoft.AspNetCore.Html.IHtmlContent containing the <input> element(s).
//
// Remarks:
// For example the default System.Object editor template includes <label> and <input>
// elements for each property in the expression's value.
// Example expressions include string.Empty which identifies the current model and
// "prop" which identifies the current model's "prop" property.
// Custom templates are found under a EditorTemplates folder. The folder name is
// case-sensitive on case-sensitive file systems.
public static IHtmlContent Editor(this IHtmlHelper htmlHelper, string expression);
您可以为 Editor Tag Helper 的表达式识别单个属性,如下所示:
@model MVC3_0.Models.Detail
<table>
<tr>
<td>Id</td>
<td>@Html.Editor("Id")</td>
</tr>
<tr>
<td>Name</td>
<td>@Html.Editor("Name")</td>
</tr>
<tr>
<td>Age</td>
<td>@Html.Editor("Age")</td>
</tr>
</table>
public IActionResult Index()
{
var model = new Detail { Id = 1, Name = "jack", Age = 12 };
return View(model);
}
结果:
您可以使用TextBox 或input 替代解决方法
@for (var i = 0; i < Model.Details.Count; i++)
{
<li>
@Html.TextBox("Details[" + i + "].Name", Model.Details[i].Name, new { htmlAttributes = new { @class = "text-field" } })
@Html.TextBox("Details[" + i + "].Age", Model.Details[i].Age, new { htmlAttributes = new { @class = "text-field" } })
</li>
}
// input tag helper
@for (var i = 0; i < Model.Details.Count; i++)
{
<li>
<input asp-for="@Model.Details[i].Name" />
<input asp-for="@Model.Details[i].Age" />
</li>
}