2

I want to format the DateTime displayed in TextBoxes without the time and to this format: 01 Jan, 2011 instead of the default 01/01/2011 for both display and edit scenarios.

I am already using the following template for DateTime in order to use datepicker. Can I somehow include formatting here?

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.DateTime?>" %>
<%: Html.TextBox("",ViewData.TemplateInfo.FormattedModelValue, new { @class = "text-box single-line" }) %>

Thanks in advance.

Tsarl
  • 277
  • 8
  • 22

2 Answers2

5
<%= Html.TextBox("",  Model.HasValue ? Model.Value.ToString("dd MMM, yyyy") : "", new { @class = "text-box single-line" }) %>

or better yet on the view model:

[DisplayFormat(DataFormatString = "{0:dd MMM, yyyy}", ApplyFormatInEditMode = true)]
public DateTime? Foo { get; set; }
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • I get an error with the first one: No overload for method .ToString accepts one argument. I will have to change my view model to use the second one so I will get back in a bit. – Tsarl Nov 03 '11 at 20:38
  • @Tsarl, oh I didn't notice you were using a nullable DateTime. In this case you will need to test whether the model has a value, but personally I would recommend the second approach. – Darin Dimitrov Nov 03 '11 at 21:12
  • Thanks again Darin. You and Jason were both very helpful and gave me correct answers at about the same time. I marked his answer as the accepted one just because he has lower reputation than you :) – Tsarl Nov 03 '11 at 21:36
  • I too have date formating with Editor Templates that is not working for me. Posted here http://stackoverflow.com/questions/18415653/mvc-4-editor-template-for-displaying-time-in-hhmm-format – Murali Murugesan Aug 24 '13 at 06:23
3

is ViewData.TemplateInfo.FormattedModelValue a datetime object?

to get the format you want out of a DateTime object use the following:

var now = DateTime.Now;
var formattedDate = now.ToString("dd MMM, yyyy");

this should work

<%= 
var theDate = Model.HasValue ? Model.Value.ToString("dd MMM, yyyy") : DateTime.Now.ToString("dd MMM, yyyy");


Html.TextBox("", theDate, new { @class = "text-box single-line" }) %>

The reason you are getting an error when you call Model.ToString("dd MMM, yyyy") is because it's a Nullable object, and it's ToString() method doesn't accept any parameters. The value of the model is a DateTime object, which does accept parameters.

Jason
  • 15,915
  • 3
  • 48
  • 72