MVC 5 Create Fixed format editorfor for datetime

1.4k views Asked by At

I'm searching for the correct way to display a TextBox which allows the user to edit a datetime value.

Currently I can display the value as I want by using DataAnnotations.

[DisplayFormat(DataFormatString = "{0:{0:HH:mm:ss dd/MM/yyyy}}", ApplyFormatInEditMode = true)]
public DateTime TimeStamp_Start { get; set; }

MVC/Razor:

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

And then I get the right visual effect:

Visual representation

But the problem now is that this is editable to a wrong format, as follows:

Visual representation of when it goes wrong when editing

How can i create a @Html.EditorFor object that show the date as in the first picture, but when editing only allows to fill in this format: {xx/xx/xxxx xx:xx:xx}?

I want the '/', ':' and ' ' (Space) values of the date format to stay put and the text the user types to fill in the gaps. I've seen it on other websites but can't seem to find the MVC/Razor code for it.

1

There are 1 answers

5
rida zd On

Please remove the data annotation and use this in cshtml

 @Html.TextBoxFor(x => x.TimeStamp_Start, new { type="date" })

that render html5 input type. you can use datetime-local to get the user machine time.

check html input type from here https://www.w3schools.com/html/html_form_input_types.asp