0

I have the following model property and attribute:

  [DataType(DataType.Date)]
    public Nullable<DateTime> DateOfBirth { get; set; }

My EditScreen.cshtml has the following part to display the date of birth:

 <div class="editor-label">
            Date of Birth
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.DateOfBirth)
            @Html.ValidationMessageFor(model => model.DateOfBirth)
        </div>

However, despite the DataType.Date attribute, the full date and time are displayed on the page, e.g. 06/04/1971 00:00:00

Why is the time part of the date still being displayed, are there any 'gotchas' that I've missed?

I've tried changing Nullable to date time but doesn't make any difference. There must be something fundamental which is preventing the date being formatted, but I have no idea what that might be, and no idea how to find out.

4
  • How about TextBoxFor instead of EditorFor ? Commented Nov 28, 2012 at 15:22
  • Nope didn't make any difference Commented Nov 28, 2012 at 16:04
  • taking the globilization culture out of web.config didn't work either Commented Nov 30, 2012 at 12:45
  • even changing the column type from date to datetime2(7) on the server didn't help. Yes I'm desperate Commented Nov 30, 2012 at 13:08

3 Answers 3

1

You probably just need to create an Editor Template to modify the date format in your EditorFor.

To do this, create a new folder (if it doesn't already exist) under Views\Shared and name it "EditorTemplates". Inside that folder add a new partial view and name it "DateTime.cshtml".

Inside the new "DateTime.cshtml" file add this code:

@model System.DateTime ?
@Html.TextBox("", (Model.HasValue ? Model.Value.ToShortDateString() : string.Empty))
Sign up to request clarification or add additional context in comments.

1 Comment

Maybe try changing your DataAnnotation to [DataType(DataType.DateTime)] as well.
0

You can try adding

   [DataType(DataType.Date)]
   [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]

Comments

0
[DataType(DataType.Date)]
(DataFormatString = "{0:MMMMMMMMMM dd,yyyy}")]
public Nullable<DateTime> DateOfBirth { get; set; }

Try this.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.