我使用了一些自定义助手,并已在 MVC 2 和 3 中成功使用它们(代码也为 on Snipplr)。当我使用 jQuery-ui 日期选择器时,助手有一些 css 逻辑,但可以很容易地删除。
public static MvcHtmlString DateTextBoxFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, string formatString, object htmlAttributes)
{
var metadata = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
string format = String.IsNullOrEmpty(formatString) ? "M/d/yyyy" : formatString;
DateTime date = metadata.Model == null ? new DateTime() : DateTime.Parse(metadata.Model.ToString());
string value = date == new DateTime() ? String.Empty : date.ToString(format);
RouteValueDictionary attributes = new RouteValueDictionary(htmlAttributes);
string datePickerClass = "date-selector";
if (attributes.ContainsKey("class"))
{
string cssClass = attributes["class"].ToString();
attributes["class"] = cssClass.Insert(cssClass.Length, " " + datePickerClass);
}
else
{
attributes["class"] = datePickerClass;
}
return helper.TextBox(ExpressionHelper.GetExpressionText(expression), value, attributes);
}
public static MvcHtmlString DateTextBoxFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression)
{
return DateTextBoxFor<TModel, TValue>(helper, expression, String.Empty, null);
}
public static MvcHtmlString DateTextBoxFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, string formatString)
{
return DateTextBoxFor<TModel, TValue>(helper, expression, formatString, null);
}