My problem was to set some html attributes (jquery-datepicker), so EditorFor was not an option for me.
Implementing a special helper method solves my problem:
ModelClass with DateTime-Property:
[DataType(DataType.Date)] [DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}", ApplyFormatInEditMode = true)] public DateTime CustomDate{ get; set; }
View with ModelClass as a model:
@Html.TextBoxWithFormatFor(m => m.CustomDate, new Dictionary<string, object> { { "class", "datepicker" } })
Helper method in a static helper class:
public static class HtmlHelperExtension { public static MvcHtmlString TextBoxWithFormatFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IDictionary<string, object> htmlAttributes) { ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData); return htmlHelper.TextBox(htmlHelper.ViewData.TemplateInfo.GetFullHtmlFieldName(metadata.PropertyName), string.Format(metadata.DisplayFormatString, metadata.Model), htmlAttributes); } }
Tobias Feb 27 '14 at 14:14 2014-02-27 14:14
source share