I have an edit object view. In this view are several DateTime? properties that are using:
model.MyDateTime ) %>
I have an editor template named DateTime that is strongly typed against a DateTime? type. The view is declared as follows:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<DateTime?>" %>
<% if( Model.HasValue ) { %>
<%= Html.TextBoxFor( x => Model, Model.Value.ToShortDateString() ) %>
<% } else { %>
<%= Html.TextBoxFor(x => Model) %>
<% } %>
The time portion is always displayed no matter what I do. I know the display template is being rendered. I’ve added static text for the if output as well as the else output and the former always shows. The incredibly odd thing is I can do:
<%= Html.Encode(Model.Value.ToShortDateString()) %>
And no time portion is displayed. I’m rather stumped. Below are the GET & POST actions I am using:
public ActionResult EditAssociate(int? Oid)
{
if (!Oid.HasValue)
return RedirectToAction("SelectReviewYearAndAssociate");
MpaNonExemptData mpaNonExemptRecord = repository.getNonExemptDataByOid(Oid.Value);
return View(mpaNonExemptRecord);
}
[HttpPost]
public ActionResult EditAssociate(MpaNonExemptData associate)
{
repository.updateNonExemptDataByOid(associate);
return View(associate);
}
As you can see, it’s really straightforward. Any thoughts?
I have looked at the following questions, but did not find an answer:
TextBoxFor Date object always shows time element
TextBoxFor Helper retains previous value even when model value is empty
You should use the
TextBoxhelper inside your editor template as contrary toTextBoxForit allows you to specify the value (the second argument of theTextBoxForhelper does not do what you think it does => it’s simply used to pass html attributes to the generated field, not to set the value):Also if this is an editor template (which is what it seems to be) you need to include it with
Html.EditorFor(x => x.MyDateTime)instead ofHtml.DisplayFor(x => x.MyDateTime)as shown in your example.