我发现我更喜欢我的观点而不是调用 Html.EditorFor(...)。这意味着编辑器和显示模板决定了我的视图中控件的命运,因此我的视图代码被清理了很多 - 它只有 html 和对编辑器的通用请求。
以下链接提供了一个在编辑器模板中工作的示例
https://jefferytay.wordpress.com/2011/12/20/asp-net-mvc-string-editor-template-which-handles-the-stringlength-attribute/
我在 String.cshtml 编辑器模板中使用了类似的模板(在 Shared/EditorTemplates 中)。
@model object
@using System.ComponentModel.DataAnnotations
@{
ModelMetadata meta = ViewData.ModelMetadata;
Type tModel = meta.ContainerType.GetProperty(meta.PropertyName).PropertyType;
}
@if(typeof(string).IsAssignableFrom(tModel)) {
var htmlOptions = new System.Collections.Generic.Dictionary<string, object>();
var stringLengthAttribute = (StringLengthAttributeAdapter)ViewData.ModelMetadata.GetValidators(this.ViewContext.Controller.ControllerContext).Where(v => v is StringLengthAttributeAdapter).FirstOrDefault();
if (stringLengthAttribute != null && stringLengthAttribute.GetClientValidationRules().First().ValidationParameters["max"] != null)
{
int maxLength = (int)stringLengthAttribute.GetClientValidationRules().First().ValidationParameters["max"];
htmlOptions.Add("maxlength", maxLength);
if (maxLength < 20)
{
htmlOptions.Add("size", maxLength);
}
}
htmlOptions.Add("class", "regular-field");
<text>
@Html.TextBoxFor(m => m, htmlOptions)
</text>
}
else if(typeof(Enum).IsAssignableFrom(tModel)) {
//Show a Drop down for an enum using:
//Enum.GetValues(tModel)
//This is beyond this article
}
//Do other things for other types...
然后我的model被标注如:
[Display(Name = "Some Field", Description = "Description of Some Field")]
[StringLength(maximumLength: 40, ErrorMessage = "{0} max length {1}.")]
public string someField{ get; set; }
而我的 View 只需调用:
<div class="editor-label">
@Html.LabelWithTooltipFor(model => model.something.someField)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.something.someField)
@Html.ValidationMessageFor(model => model.something.someField)
</div>
您可能还注意到我的 String.cshtml 编辑器模板也可以自动处理 Enum,但这开始偏离当前主题,所以我取消了该代码,我在这里只说字符串编辑器模板可以拉额外的重量,很可能谷歌对此有一些意见https://www.google.com/search?q=string+editor+template+enum
Label With Tooltip For 是一个自定义 HTML 帮助器,它只是将描述放入标签标题中,以获取有关每个标签的鼠标悬停的更多信息。
如果您想在编辑器模板中执行此操作,我建议您使用此方法。