TextBoxFor Date object always shows a time element.

I am having a problem displaying / editing a date in MVC 3.

I set the property of my data class as follows (the data is actually provided by the Linq2Sql object):

[DisplayName("Date of Birth")] [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}", NullDisplayText = "")] public DateTime DoB { get; set; } 

In the view, I then:

 @Html.TextBoxFor(m => m.DoB, new { @class = "date" }) 

The problem is that the text field always shows the time part of the date, for example. '18 / 10/2010 00:00:00 '

I know I can overcome this problem using the standard Html.TextBox

 @Html.TextBox("DoB", Model.DoB.ToShortDateString()) 

but I really want to be able to control this from a data model.

I found articles on the Internet that show that this works, but I cannot repeat their success.

Any help / advice would be appreciated.

+4
source share
3 answers

If you want data annotation attributes like DisplayFormat to have some kind of effect you should use:

 @Html.EditorFor(m => m.DoB) 

Check out the next blog post from Brad Wilson, which explains how model metadata works in ASP.NET MVC.

The downside is that now you can no longer specify a class. One possible solution would be to do this:

 <div class="input-date"> @Html.EditorFor(m => m.DoB) </div> 

and then style:

 .input-date input { ... } 

or you can also write a custom DataAnnotationsModelMetadataProvider that allows you to specify attributes such as class, size, maximum length, ... using data annotations.

+5
source

Proper Use [DataType(DataType.Date)]

0
source

I stumbled upon this and had the same problems. I found that separating the display and model values ​​allowed me to handle the date display in any format I want:

 @Html.TextBoxFor(m => m.DoB, new {@class="date",Value=Model.DoB.ToString(DateFormat.DdMmYyyy) }) 

This allows me to bind values ​​to and from the model, but I can handle the output format.

0
source

Source: https://habr.com/ru/post/1343078/


All Articles