Posted By

nkirkes on 01/19/11


Tagged

MVC helpers c#


Versions (?)

Html.DateTextBoxFor


 / Published in: C#
 

I use these helper methods to create a jQuery based date text box with appropriate short date formatting.

  1. public static MvcHtmlString DateTextBoxFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, string formatString, object htmlAttributes)
  2. {
  3. var metadata = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
  4. string format = String.IsNullOrEmpty(formatString) ? "M/d/yyyy" : formatString;
  5. DateTime date = metadata.Model == null ? new DateTime() : DateTime.Parse(metadata.Model.ToString());
  6. string value = date == new DateTime() ? String.Empty : date.ToString(format);
  7. RouteValueDictionary attributes = new RouteValueDictionary(htmlAttributes);
  8. string datePickerClass = "date-selector";
  9. if (attributes.ContainsKey("class"))
  10. {
  11. string cssClass = attributes["class"].ToString();
  12. attributes["class"] = cssClass.Insert(cssClass.Length, " " + datePickerClass);
  13. }
  14. else
  15. {
  16. attributes["class"] = datePickerClass;
  17. }
  18. return helper.TextBox(ExpressionHelper.GetExpressionText(expression), value, attributes);
  19. }
  20.  
  21. public static MvcHtmlString DateTextBoxFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression)
  22. {
  23. return DateTextBoxFor<TModel, TValue>(helper, expression, String.Empty, null);
  24. }
  25.  
  26. public static MvcHtmlString DateTextBoxFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, string formatString)
  27. {
  28. return DateTextBoxFor<TModel, TValue>(helper, expression, formatString, null);
  29. }

Report this snippet  

You need to login to post a comment.