I have an Editor Template for my Date fields which sets the current date if the field is null.
@model Nullable<DateTime>
@{
var date = Model as DateTime?; // local reference to a DateTime?
if (!date.HasValue // check if it is not null
|| date.Equals(default(DateTime))) // check if it is not default 01/01/0001
{
date = DateTime.Now;
}
@Html.TextBox("", String.Format("{0:d}", date.Value.ToShortDateString()), new { @class = "date" })
}
I would like to apply this template to only my Create Views.
When I edit a record the above code populates the current date for fields that I had intentionally left as null as the date was unknown.
Wondering if my code can be amended to accommodate this?
Any help would be appreciated.
There are a couple ways you could do this.
First way is to pass in a flag through your ViewData, something like this:
Then update your template:
Another way is to default this to
DateTime.Nowin your controller — or even better, a mapper — when you create a new model. This separates the concerns of setting the default where it belongs, in your controller/mapper instead of the view.