Format MVC default Date (01/01/0001) to be empty

2020-06-24 08:32发布

问题:

my Razor form code

<div class="form-group">
    @Html.LabelFor(model => model.achPayDate, htmlAttributes: new { @class = "control-label col-md-7" })
    @Html.DisplayFor(model => model.achPayDate, new {@class="date"})
</div>

my cs code

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

01/01/0001 is displayed when the achPayDate=0001-01-01T00:00:00 , I want to suppress the date to be blank. How can I do that??

回答1:

You can do the following

  1. In your MVC Project => Views => Shared , create new folder DisplayTemplates
  2. Create new view under DisplayTemplates folder and call it Date.cshtml

the code of Date.cshtml

@model DateTime?
@if(Model!=null && Model!=DateTime.MinValue)
{
   @string.Format("{0:MM/dd/yyyy}",Model)
}

the code of your Model

[DataType(DataType.Date)]
public DateTime? achPayDate { get; set; }

this way will make all DateTime with data annotation [DataType(DataType.Date)] to follow same behavior, and also you can do the same for the EditorTemplates

you can get more information about EditorTemplates and DisplayTemplates here

Hope this will help you



回答2:

For normal DateTimes, if you don't initialize them at all then they will match DateTime.MinValue, because it is a value type rather than a reference type.

You can also use a nullable DateTime, like this:

DateTime? MyNullableDate;

Or the longer form:

Nullable<DateTime> MyNullableDate;

or use that:

private DateTime? _achPayDate = null;
public DateTime? achPayDate { get {return _achPayDate ; } set{_achPayDate = value;} }