Formatting nullable DateTime fields in strong typed View

不问归期 提交于 2020-01-01 18:17:18

问题


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?


回答1:


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";



回答2:


I know this is very late but I was researching another problem and came across this issue. There is a way to only show the date part which does not require presentation layer formatting.

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

Using this will ensure that everywhere you bind to this property on your View, only the date will show

Hope this helps somebody




回答3:


To do this in your VIEW, you can use Razor syntax, as well:

 @Html.TextBox("BornDate", item.BornDate.HasValue ? item.BornDate.Value.ToShortDateString():"") 



回答4:


You can do this, it will work with Nullable model types:

@model DateTime?
@{
    object txtVal = "";
    if (Model.HasValue) 
    {
        txtVal = Model.Value;
    };
}
@Html.TextBoxFor(x => Model, new {Value = string.Format(ViewData.ModelMetadata.EditFormatString, txtVal))



回答5:


Another way I've tackled this issue is by adding format to the TextBoxFor

@Html.TextBoxFor(model => model.BornDate, "{0:MM/dd/yyyy}", new { id = "bornDate" })


来源:https://stackoverflow.com/questions/3684015/formatting-nullable-datetime-fields-in-strong-typed-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!