/ Published in: C#
I use these helper methods to create a jQuery based date text box with appropriate short date formatting.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
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 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); }