Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
915 views
in Technique[技术] by (71.8m points)

asp.net mvc - show only the date in @Html.EditorFor helper

I am trying to populate @Html.EditorFor helper. I have created a view model with the below property

[DataType(DataType.Date, ErrorMessage="Date only")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yy}", ApplyFormatInEditMode = true)]
public DateTime? YearBought { get; set; }

and my helper is set up as below (a)

@Html.ValidationMessageFor(m => m.YearBought)
@Html.EditorFor(model => model.YearBought, new { @type = "date" })

I have also tried (b)

@Html.ValidationMessageFor(m => m.YearBought)
@Html.EditorFor(model => model.YearBought.Value.Date)

Using the above format (a) nothing is displayed. Using the above format (b) 12/05/2014 00:00:00 is displayed in textbox format.

I am trying to achieve a datepicker format without a time displayed

I have reviewed several other questions but cant see what i've done different.

When I look in my database, the value is save as 2014-05-12 and when I am saving the value the EditorFor helper generates the required input facility

questions reviewed

first second third....the list goes on

EDIT just opened the console in chrome dev tools and so this message

The specified value "12/05/14" does not conform to the required format, "yyyy-MM-dd"

I thought DisplayFormat(DataFormatString = "{0:dd/MM/yy}" was defining how to display my date?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to use the ISO format when using type="date"

[DataType(DataType.Date, ErrorMessage="Date only")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime? YearBought { get; set; }

This will display the date in the browsers culture.

Note there is no need to add @type = "date". The EditorFor() method will add that because of the DataType attribute. Note also that type="date" is only supported in Chrome (FireFox and IE will just generate a normal textbox)

If you do want to display the format dd/MM/yyyy in a standard textbox then you can use

@Html.TextBoxFor(m => m.YearBought, "{0:dd/MM/yyyy}")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...