The TextBoxes can be made ReadOnly by setting the HTML ReadOnly attribute using the HtmlAttributes parameter in Html. TextBox and Html. TextBoxFor helper functions.
The HtmlHelper class includes two extension methods TextBox() and TextBoxFor<TModel, TProperty>() that renders the HTML textbox control <input type="text"> in the razor view. It is recommended to use the generic TextBoxFor<TModel, TProperty>() method, which is less error prons and performs fast.
Show activity on this post. TextBoxFor: It will render like text input html element corresponding to specified expression. In simple word it will always render like an input textbox irrespective datatype of the property which is getting bind with the control. EditorFor: This control is bit smart.
MVC4 has solved this problem by adding a new TextBoxFor
overload, which takes a string format parameter. You can now simply do this:
@Html.TextBoxFor(m => m.EndDate, "{0:d MMM yyyy}")
There's also an overload that takes html attributes, so you can set the CSS class, wire up datepickers, etc:
@Html.TextBoxFor(m => m.EndDate, "{0:d MMM yyyy}", new { @class="input-large" })
<%= Html.TextBoxFor(model => model.EndDate, new { @class = "jquery_datepicker", @Value = Model.EndDate.ToString("dd.MM.yyyy") })%>
[DisplayName("Start Date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
public DateTime StartDate { get; set; }
Then:
<%=Html.EditorFor(m => m.StartDate) %>
Or use the untyped helpers:
<%= Html.TextBox("StartDate", string.Format("{0:d}", Model.StartDate)) %>
This worked for me.
@Html.TextBoxFor(m => m.DateOfBirth, "{0:MM/dd/yyyy}", new { size = "12", @class = "DOB", tabindex = 121 })
TL;DR;
@Html.TextBoxFor(m => m.DOB,"{0:yyyy-MM-dd}", new { type = "date" })
Applying [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
didn't work out for me!
Explanation:
The date of an html input
element of type date
must be formatted in respect to ISO8601, which is: yyyy-MM-dd
The displayed date is formatted based on the locale of the user's browser, but the parsed value is always formatted yyyy-mm-dd.
My experience is, that the language is not determined by the Accept-Language
header, but by either the browser display language or OS system language.
In order to display a date property of your model using Html.TextBoxFor
:
Date property of your model class:
public DateTime DOB { get; set; }
Nothing else is needed on the model side.
In Razor you do:
@Html.TextBoxFor(m => m.DOB,"{0:yyyy-MM-dd}", new { type = "date" })
Don't be afraid of using raw HTML.
<input type="text" value="<%= Html.Encode(Model.SomeDate.ToShortDateString()) %>" />
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