I just came across a very interesting issue. If I use ViewData to pass a DateTime value to the view and then display it inside a textbox, even though I'm using String.Format in the exact same manner, I get different formatting results when using the Html.TextBox helper.
<%= Html.TextBox("datefilter", String.Format("{0:d}", ViewData["datefilter"]))%>
<input id="test" name="test" type="text" value="<%: String.Format("{0:d}", ViewData["datefilter"]) %>" />
The above code renders the following html:
<input id="datefilter" name="datefilter" type="text" value="2010-06-18" />
<input id="test" name="test" type="text" value="18/06/2010" />
Notice how the fist line that uses the Html helper produces the date format in one way while the second one produces a very different output. Any ideas why?
Note: I'm currently in Brazil, so the standard short date format here is dd/MM/yyyy.
Best Answer
The reason this happens is because the TextBox helper uses the value stored inside
ViewData["datefilter"]
because its name isdatefilter
and completely ignores the second argument you are passing which is supposed to format the date. Try changing the name of the textbox.A better solution is to use editor templates and strongly typed views instead of
ViewData
. Here's an example.Model:
Controller:
View: