2011-09-09 33 views
2

我寫了一個自定義的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(我可以做,如果一切都失敗了)?

+0

仍然想知道是否有這個答案... – Kizmar

回答

0

我最近實施了類似的東西,以顯示標註的「說明」屬性,並且將其輸出到屏幕上:

public static MvcHtmlString DescriptionFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression) { 
     var metadata = ModelMetadata.FromLambdaExpression(expression, helper.ViewData); 
     var description = metadata.Description; 

     return MvcHtmlString.Create(description); 
    } 

I輸出這些助手工具提示類型的控件。我考慮實現我自己的工具提示屬性,但它似乎比我需要的更多...