ASP.Net MVC DisplayFormat

In my model, I have the following DataAnnotations on one of my properties

[Required(ErrorMessage = "*")] [DisplayFormat(DataFormatString = "{0:d}")] [DataType(DataType.Date)] public DateTime Birthdate { get; set; } 

The required annotation works fine, I added another 2 to try to remove the time. It binds to the input in the view using

 <%=Html.TextBoxFor(m => m.Birthdate, new { @class = "middle-input" })%> 

However, whenever the view loads, I still get the time that appears in the input field. Is there a way to remove this using DataAnnotations?

+45
asp.net-mvc data-annotations
Jan 04 '10 at 19:52
source share
3 answers

The [DisplayFormat] attribute is used only in EditorFor / DisplayFor, and not in raw HTML APIs such as TextBoxFor.

+83
Jan 05 '10 at 7:56
source share

Since Brad said that it does not work for TextBoxFor, but you will also need to remember adding the ApplyFormatInEditMode method if you want it to work for EditorFor.

 [DataType(DataType.Date), DisplayFormat( DataFormatString="{0:dd/MM/yy}", ApplyFormatInEditMode=true )] public System.DateTime DateCreated { get; set; } 

Then use

 @Html.EditorFor(model => model.DateCreated) 
+26
Apr 30 2018-12-12T00:
source share

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); } } 
+5
Feb 27 '14 at 14:14
source share



All Articles