如何创建 HTML Helper 来扩展 TextBoxFor?

how to create HTML Helper to extend TextBoxFor?

您好,我有以下代码行:

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

如何编写帮助程序看起来像

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

格式字符串和 类 在这个新助手中的什么位置?

为此,您需要使用 extension method 创建 custom html helpers 试试下面的代码

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);
    }

}
}