我寫了一個自定義的DataAnnotation,完美地工作,除非我使用ViewModel而不是實際的模型本身。自定義DataAnnotation&ViewModels
與模型,數據標註呈現的東西的影響:
<label class="tooltip" for="title">Enter a title.</label>
當我使用一個視圖模型,數據註解仍然呈現同樣的事情。這裏的問題是「for」應該是「Product_title」而不是「title」。
這是我寫的的HtmlHelper從數據註解呈現標籤:
(來自asp.net MVC extending DataAnnotions兩者)
public static MvcHtmlString TooltipFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression) {
var exp = (MemberExpression)expression.Body;
foreach (Attribute attribute in exp.Expression.Type.GetProperty(exp.Member.Name).GetCustomAttributes(false)) {
if (typeof(Tooltip) == attribute.GetType()) {
return MvcHtmlString.Create("<label class=\"tooltip\" for=\"" + exp.Member.Name + "\">" + ((Tooltip)attribute).Description + "</label>");
}
}
return MvcHtmlString.Create("");
}
我在表達對象周圍挖找出哪些屬性保存的是模型屬性最終成爲輸入ID的名稱; 「exp.Member.Name」。
現在,我使用ViewModel,顯然需要不同的東西,因爲「exp.Member.Name」仍然返回「title」而不是「Product_title」,最終成爲輸入字段的ID。
那麼,是否有一個屬性,我可以使用,而不是「Member.Name」,將始終返回正確的ID,或者我將不得不解決這個問題與JavaScript(我可以做,如果一切都失敗了)?
仍然想知道是否有這個答案... – Kizmar