Reputation: 4415
I am having a problem displaying/editing a date in MVC 3.
I have set up my data class property as follows (the data is actually provided by a 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 have:
@Html.TextBoxFor(m => m.DoB, new { @class = "date" })
The problem is, the text box always shows the time portion of the date, e.g. '18/10/2010 00:00:00'
I know I can get over this problem by using a standard Html.TextBox
@Html.TextBox("DoB", Model.DoB.ToShortDateString())
but I really want to be able to control this from the data model.
I have found articles on the web that suggest that this works, but I can't repeat their success.
Any help/advice would be appreciated.
Upvotes: 4
Views: 4776
Reputation: 111
I have stumbled upon this and had the same problems. I found splitting the display and model values allowed me to handle the display of a date in any format I wish:
@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.
Upvotes: 0
Reputation: 1038710
If you want the data annotations attributes such as DisplayFormat
to have any effect you should use:
@Html.EditorFor(m => m.DoB)
Checkout the following blog post from Brad Wilson which explains how model metadata works in ASP.NET MVC.
The drawback is that now you cannot specify the class anymore. 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 could also write a custom DataAnnotationsModelMetadataProvider which would allow you to specify attributes such as class, size, maxlength, ... using data annotations.
Upvotes: 5