Reputation: 41
I’m working on ASP.NET application, and I have an issue with date formatting. TextBoxFor is displaying Date Format instead of date.
Regional Settings:
United Kingdom, date format: “yyyy-mm-dd”.
.NET Globalization - IIS Settings:
Culture: Invariant Language (Invariant Country)
Enable Client Based Culture: false
UI Culture: Invariant Language (Invariant Country)
File: Windows-1252
Requests: utf-8
Response Headers: utf-8
Responses: utf-8
MainView (I have tried ToShortDateString()
and ToString("d")
) :
<td>
@item.InvoiceDate.ToShortDateString()
</td>
<td>
@item.DueDate.ToString("d")
</td>
Edit View:
<div class="form-group">
<div class="col-md-10">
@Html.Label("Invoice Date:")
<div class="fiveSpace"></div>
@Html.TextBoxFor(model => model.InvoiceDate, "{0:d}", new { type = "date" })
@Html.ValidationMessageFor(model => model.InvoiceDate)
</div>
</div>
<div class="form-group">
<div class="col-md-10">
@Html.Label("Due Date:")
<div class="fiveSpace"></div>
@Html.TextBoxFor(model => model.DueDate, "{0:d}", new { type = "date" })
@Html.ValidationMessageFor(model => model.DueDate)
</div>
</div>
Model:
[Required(ErrorMessage = "Please select Invoice Date.")]
public DateTime? InvoiceDate { get; set; }
[Required(ErrorMessage = "Please select Due Date.")]
public DateTime? DueDate { get; set; }
And result: Table row
Once I try to edit dates: Date and Inspect element
Correct value is stored in "value" but TextBoxFor displays date format. Also, when I have changed regional setting to other country, in MainView I always received dates in format "dd/mm/yyyy" and in edit view dates were displayed with US format, "mm/dd/yyyy".
I have tried:
<globalization uiCulture="en-GB" culture="en-GB" />
in web.config
[DisplayFormat(DataFormatString = "{0:d}"]
to modelIs the problem on my side, or IIS?
Upvotes: 2
Views: 2797
Reputation: 41
Resolved.
I've replaced mentioned TextBoxFor
with:
@Html.TextBoxFor(model => model.InvoiceDate, new { @type = "date", @Value = Model.InvoiceDate.Value.ToString("yyyy-MM-dd") })
and it works.
Upvotes: 1
Reputation: 26
The TextBoxFor
with type="date"
converts it to the <input type="date">
HTML tag which doesn't support date format customization according to the MDN.
It can be achieved by some 3rd-party JS libraries like Masked Input Plugin for jQuery or datetime-input web component
Upvotes: 0