2016-02-29 52 views
0

您好我已經有了的代碼下面一行:如何創建HTML助手來擴展TextBoxFor?

@Html.TextBoxFor(m => m.StartDate,"{0:MM/dd/yy hh:mm:ss}",new{@class="form-control axDateTimePicker"}) 

如何寫幫手,看起來像

@Html.DateTimePickerHelper(m=>m.StartDate) 

在格式字符串和類是這個新幫手裏面?

回答

5

爲此,您需要使用extension method 創建試試下面的代碼

namespace System.Web.Mvc 
{ 

public static class CustomHtmlHelpers 
{ 

    public static MvcHtmlString DateTimePickerHelper<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes) 
    { 
     var attributes = new RouteValueDictionary(htmlAttributes); 
     string format = "{0:MM/dd/yy hh:mm:ss}"; 
     return System.Web.Mvc.Html.InputExtensions.TextBoxFor(htmlHelper, expression, format, attributes); 
    } 

} 
}