如何创建HTML Helper来扩展TextBoxFor?

kam*_*lws 0 html asp.net asp.net-mvc html-helper

嗨,我有以下代码行:

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

如何写帮手看起来像

@Html.DateTimePickerHelper(m=>m.StartDate)
Run Code Online (Sandbox Code Playgroud)

格式字符串和类在这个新助手里面的位置?

shu*_*shu 5

为此,您需要custom html helpers使用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);
    }

}
}
Run Code Online (Sandbox Code Playgroud)