我發現我更喜歡我的觀點只是調用Html.EditorFor(...)。這意味着編輯器和顯示模板決定了我的視圖中控件的命運,這樣我的視圖代碼就被清理了很多 - 它只是對編輯器有html和通用請求。
以下鏈接給在得到這個工作的工作樣本的編輯模板 https://jefferytay.wordpress.com/2011/12/20/asp-net-mvc-string-editor-template-which-handles-the-stringlength-attribute/
我用我的String.cshtml編輯模板類似(進去共享/ 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...
然後我模式被註釋,如:
[Display(Name = "Some Field", Description = "Description of Some Field")]
[StringLength(maximumLength: 40, ErrorMessage = "{0} max length {1}.")]
public string someField{ get; set; }
而且我查看簡單地調用:
<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的,但是現在已經開始脫離當前的話題,所以我沒有那個c賦,我就在這裏說,該字符串編輯器模板可以拉額外的重量,並有可能谷歌已經對https://www.google.com/search?q=string+editor+template+enum
標籤用工具提示成才的是一個自定義HTML幫助,只是下降的描述到標籤的標題,有關每個標籤的鼠標懸停的更多信息。
如果您想在編輯器模板中執行此操作,我會推薦此方法。
這看起來不錯!在Html.EditorForModel()中可以使用與上面提到的類似的東西嗎? 謝謝你的幫助。 – frostshoxx
@frostshoxx您可以使用[UIHintAttribute](http://msdn.microsoft.com/zh-cn/library/system.componentmodel.dataannotations.uihintattribute.aspx)併爲每種數據類型製作自定義模板。我還沒有嘗試過。 – Eranga