views:

26

answers:

1

Hello,

I have a Person class with a BornDate property in my model defined as

[DisplayName("Born Date")]
public DateTime? BornDate { get; set; }

I use this field in my view as

<td style="white-space:nowrap">
    <%= Html.LabelFor(model => model.BornDate)%>
    <br />
    <%= Html.TextBoxFor(model => model.BornDate, new { id = "bornDate" })%>
    <%= Html.ValidationMessageFor(model => model.BornDate, "*")%>
</td>

The problem is that when I am editing a Person instance with the BornDate text box is formatted as

dd/MM/yyyy hh.mm.ss

while I would like to format it without the time part ("dd/MM/yyyy"). I am not able to use the toString method with the format string because it is a nullable field.

what can I do?

A: 

You should be able to use Value. Just check it isn't null first.

var displayDate = model.BornDate.HasValue ? model.BornDate.Value.ToString("yyyy") : "NoDate";
Bigfellahull
First of all thanks for your response. Where do I have to put this code? If I put it inside the TextBoxFor function, within the lambda expression, I get an InvalidOperationException "Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions."
Lorenzo
Hrm... yeah I forgot the fact you are using strongly typed helpers. I think the only way round this is to use the TextBox helper: <%= Html.TextBox("date", Model.BornDate.Value.ToString("yyyy"), new { id = "bornDate" }) %>
Bigfellahull
Ok! This sure will work... thank you!
Lorenzo