asp.net mvc How to display default value on a date type textbox

user2093360 picture user2093360 · May 29, 2013 · Viewed 14.8k times · Source

I'm developing in asp.net mvc. I want to have a textbox which is date type, so there's a shortcut that user can click and select a date instead of type in. Meanwhile I want the textbox to display a default date value.

I have tried 2 ways: <input type="date" name="toDate" value="@DateTime.Today.Date.ToShortDateString()" />

@Html.TextBox("date", DateTime.Now.ToShortDateString(), new { type = "date"})

But these two methods generate textbox with 'dd/mm/yyyy' displaying in the box instead of the the default value I set. When I right click on the textbox and inspect element, I can see that there is a value of current date, but it can't show in the textbox!

When I replace the type="date" to type="text", I can see the default value on textbox. But there's no shortcut for me to select a date, it only allows me to type in.

How do I do this to reserve both the shortcut and default value?

Answer

cat_minhv0 picture cat_minhv0 · May 29, 2013

I think you want HTML5 date picker. It depends on web browser you are using. Currently, Google chrome and Opera support that.

<input type="date" value="2012-10-10"/>
@Html.TextBox("date", DateTime.Now.ToString("yyyy-MM-dd"), new { type = "date" })