Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - Why is my date input not reading the model value?

I'm a server side guy trying to teach myself a bit of CSS, Javascript, jQuery etc. I have written a little test project that loads up a model and displays the values in simple text boxes. Works OK, as you can see:

enter image description here

But of course, I want to display those dates appropriately. So let me change those input types to "date". Here's the Razor code:

@Html.TextBoxFor(m => m.Date, new { @type="date", @id="ondate" })

Well, that worked.... sort of. I mean, it now displays as a date picker... but it's no longer displaying the model's date!

enter image description here

What am I doing wrong?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

The type="date" attribute renders the browsers HTML5 datepicker. In order for this to work correctly, the format needs to be yyyy-MM-dd (ISO format), so it needs to be

@Html.TextBoxFor(m => m.Date, "{0:yyyy-MM-dd}", new { @type="date" })

Alternatively you can set data attributes on the property

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

and use

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

which adds the type="date" attribute and uses the correct format.

Side notes:

  1. The HTML5 datepicker is only supported in recent versions of Chrome
  2. Using EditorFor() (in MVC-4) will not allow you to set the id attribute, but its not clear why you would need to change the default id="Date" to id="ondate"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...