3

I'm having trouble trying to write a form with time field using ASP.NET MVC 4.

Model:

class Abcde {
    [DataType(DataType.Time)]
    public DateTime ATime { get; set; }
}

View.cshtml

...
@Html.EditorFor(m => m.ATime)
@Html.ValidationMessageFor(m => m.ATime)

The validation always failed when I tried to input a time (hh:nn:ss), and said it was not in the corrent format, so i have to input a date instead. My Question is should I change the type to TimeSpan? Or is there any other way?

4 Answers 4

10
[Required]
[DataType(DataType.Time)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:H:mm}")]
public DateTime Time { get; set; }`

Try this, you can format in the DataFormatString the way you want it to work for you, im using it in a project now and it's working for me.

Sign up to request clarification or add additional context in comments.

2 Comments

Didn't work for me, getting "--:-- --" in the text box, no picker. Inspecting the source gives the expected "4:00" for the html value.
If someone is also struggling why it doesn't work when everybody says it does, try {0:HH:mm} instead of {0:H:mm}
4

Actually this is what worked for me.

[DataType(DataType.Time)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:HH:mm}")]
public DateTime Hour { get; set; }

Comments

0
[Required]
[DataType(DataType.Time)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:HH:mm}")]
public DateTime Time { get; set; }

This code is correct. But it only works when you use EditorFor instead of TextBoxFor.

Comments

-2

Use:

[Required]
[DataType(DataType.Time)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:HH:mm:ss}")]
public DateTime FieldTime{ get; set; }

You need to match your date validation with the format that works internally for this annotation. So, adding the ApplyFormat passing a String Pattern you can get it.

2 Comments

This may be the correct answer, but please explain why it's the correct answer :)
@Willian write some explanation of your code what and why. Thanks

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.