Weird problem that is probably very obvious. In my view model I have a date, which I set in the controller. When I render the textbox in the view, it is empty.
View model:
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}")]
public DateTime DateStart { get; set; }
Controller:
//GET: InvoicePrice
public ActionResult Index(InvoicePriceViewModel model)
{
model.DateStart = DateTime.Now;
return View(model);
}
HTML of view:
<p>
Date:<br />
@Html.TextBoxFor(model => model.DateStart, new { @class = "form-control", placeholder = "Invoice date", type = "date" })
</p>
When I open this, I get the empty textbox here:

And I would expect to see "28-11-2017" as my current date.
I guess I am missing something obvious here. But what is it?
There is actually a couple of issues here and I'll try to explain them.
The first problem is that date input accepts values only in yyyy-mm-dd format and displays them based on the browser localization settings:
One thing to note is that the displayed date format differs from the actual value — the displayed date format will be chosen based on the set locale of the user's browser, whereas the date value is always formatted yyyy-mm-dd.
This means you need to change your DataFormatString and also set ApplyFormatInEditMode to true:
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
However it still won't have any effect because in order for your custom format to be taken into account you need to use Html.EditorFor:
@Html.EditorFor(model => model.DateStart,
new { htmlAttributes = new { @class = "form-control", placeholder = "Invoice date" } })
Or you can ignore DisplayFormatAttribute and specify the format in the Html.TextBoxFor:
@Html.TextBoxFor(model => model.DateStart, "{0:yyyy-MM-dd}",
new { @class = "form-control", placeholder = "Invoice date", type = "date" })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With