slandau
slandau

Reputation: 24102

Change display of DateTime in MVC

<%= Html.TextBoxFor(m => m.Trx.TradeDate, new { @class = "economicTextBox", propertyName = "Trx.TradeDate", dontRegisterNewIndication = true })%>

Since this is a TextBoxFor, I can't just change the way it's displayed (I don't think?), because I have to have that specific property value I'm binding this to.

This is displaying the full DateTime though - 5/18/2011 10:21:22 AM

How do I get it to only display the 5/18/2011 portion?

Should I do it through Javascript? This field is made as a JQuery DatePicker field as well.

Upvotes: 2

Views: 331

Answers (1)

moribvndvs
moribvndvs

Reputation: 42505

You can define an EditorTemplate for DateTime, either in the EditorTemplates folder in your view, or in /Views/Shared/EditorTemplates.

Then call <%= Html.EditorFor(m => m.DateTimeProp) %>.

\Views\Shared\EditorTemplates\DateTime.ascx:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<DateTime?>" %>
<%= Html.TextBox(ViewData.TemplateInfo.GetFullHtmlFieldName(string.Empty), Model.HasValue ? Model.Value.ToString("dd-MM-yyyy") : string.Empty) %>

Alternately:

You can also add your own HtmlHelper extension, like DateTimeTextBoxFor. Unfortunately, the templates used by the ____For default extensions have a rather static template.

Another Alternative:

You can use Data Attributes to control the data type and format, however, I think you still need to use EditorFor to get those to work (although, it wouldn't require a separate ASCX file).

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

<%= Html.EditorFor(m => m.DateTimeProp) %>

Upvotes: 1

Related Questions