<tr>
<td>
@Html.Label("Notes") </td><td> @Html.TextArea("Notes")
</td></tr>
<tr><td>
@Html.Label("Action Date")</td><td> @Html.TextBoxFor(m => m.Due, new { @class = "dateTimePicker" })</td><td>
@Html.ValidationMessageFor(m => m.Due)
</td></tr>
无论如何,我可以创建一个模板,它将采用任何 @HTML.Label
、@Html.Textbox
等,以及它们的 for
副本并将它们正确地放在 table 上?无需我用表格标记污染我的所有 View 。
最佳答案
你当然可以。我根据您的示例代码拼凑了一个快速示例:
给定一个基本模型:
public class Foo
{
public string Notes { get; set; }
[Required]
[DisplayName("Action Date")]
public DateTime Due { get; set; }
}
还有这个简单的 Controller :
var model = new Foo { Notes = "Some Note String", Due = System.DateTime.Now };
return View(model);
您可以从您的 View 中调用编辑器模板:
@Html.Editor("Editor", "Foo", Model)
给定这个模板:
@model StackExamples.Models.Foo
<table>
<tr>
<td>
@Html.LabelFor(x => x.Notes)
</td>
<td>
@Html.TextAreaFor(x=>x.Notes)
</td>
</tr>
<tr>
<td>
@Html.LabelFor(x=>x.Due)
</td>
<td>
@Html.TextBoxFor(m => m.Due, new { @class = "dateTimePicker" })
</td>
<td>
@Html.ValidationMessageFor(m => m.Due)
</td>
</tr>
</table>
并根据需要呈现输出,而无需在 View 中添加额外的表格标记。
关于c# - ASP.NET MVC 3 : Editor templates for fields,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8271767/