我想用模板将模型的一些控件分组(最好不要在 C# 中硬编码)。如果布局发生变化,我可以只编辑模板的 html,而不是在每个视图中更改它。
这是我到目前为止所得到的:
Views\EditorTemplates\InputBlock.cshtml
<section class="pure-g">
@foreach (KeyValuePair<string, object> item in ViewData)
{
if (ViewData.ModelMetadata.Properties.Any(x => x.PropertyName == item.Key))
{
<div class="pure-u-1-2">
@Html.Label(item.Key)
@Html.Editor(item.Key)
@Html.ValidationMessage(item.Key)
</div>
}
}
</section>
我正在使用这样的模板:
@Html.EditorFor(model => model, "InputBlock", new { Model.FirstName, Model.LastName, Model.LastLogin, Model.Id })
这有效,它呈现所有控件,因为它们应该具有正确的类型。
问题是它忽略了添加到模型中的任何属性,例如[Required]或[DisplayName],因此标签显示属性名称而不是设置为 DisplayName 的值,即使 ModelMetadata 中的属性设置了正确的 DisplayName 也是如此。
服务器端验证也可以正常工作。定义[Required]或[StringLength]时不添加不显眼的验证属性,仅设置特定数据类型的默认属性(如 datetime 或 int)
如何轻松地将模板中的多个控件组合在一起,而 Attributes 仍然可以工作,最好在不重新编译项目的情况下进行更改?