Reputation: 2259
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
Upvotes: 1
Views: 2490
Reputation: 661
@Html.TextBoxFor(m => m.YourDateField,
new { @onkeydown = "return false;", @class = "yourCssClass",
@Value = (Model.YourDateField.HasValue) ?
Model.YourDateField.Value.ToShortDateString() : ""})
Upvotes: 0
Reputation: 1038710
You should use the TextBox
helper inside your editor template as contrary to TextBoxFor
it allows you to specify the value (the second argument of the TextBoxFor
helper 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):
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<DateTime?>" %>
<% if(Model.HasValue) { %>
<%= Html.TextBox("", Model.Value.ToShortDateString()) %>
<% } else { %>
<%= Html.TextBox("") %>
<% } %>
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 of Html.DisplayFor(x => x.MyDateTime)
as shown in your example.
Upvotes: 3