2014-03-05 37 views
6

我正在尋求擴充「Html.TextBoxFor」擴展以滿足某些特定的客戶端需求。MVC5 HTMLHelper擴展不會返回預期的內容

作爲一個全面的檢查,我上手簡單,只是創建了一個測試擴展方法,這將直接委託給現有的功能:

public static class HtmlExtensions 
{ 
    public static MvcHtmlString Test<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression) 
    { 
     return htmlHelper.TextBoxFor(expression); 
    } 
} 

一切似乎工作,直到我想這對標記了一個模型註解,即:

public class TestRoot 
{ 
    [Display(Name = "Max Length 10")] 
    [Required] 
    [StringLength(10)] 
    public string MaxLength10 { get; set; } 
} 

當我調用內置TextBoxFor功能,我得到的所有預期的加價,即:

@ Html.TextBoxFor(E => e.MaxLength10)

<input data-val="true" data-val-length="The field Max Length 10 must be a string with a maximum length of 10." data-val-length-max="10" data-val-required="The Max Length 10 field is required." id="MaxLength10" name="MaxLength10" type="text" value=""> 

當我打電話給我的分機,我預料的一樣的內容,而是我得到這個:

@ Html.Test(E => e.MaxLength10)

<input id="MaxLength10" name="MaxLength10" type="text" value=""> 

發生了什麼事的所有漂亮的數據標註標籤?

回答

1

我有一個類似的擴展方法,可以創建可正常工作的水印文本框。試試看看它是否解決了你的問題。還要看看ModelMetadata實例是否正確創建。

public static MvcHtmlString WatermarkTextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes = null) 
{ 
    ModelMetadata metadata = ModelMetadata.FromLambdaExpression<TModel, TProperty>(expression, htmlHelper.ViewData); 
    string watermark = !String.IsNullOrEmpty(metadata.Watermark) ? metadata.Watermark : metadata.DisplayName; 
    var attributes = htmlHelper.MergeAttributes(htmlAttributes, new { placeholder = watermark }); 

    return htmlHelper.TextBoxFor<TModel, TProperty>(expression, attributes); 
}