I am kind of stumped because, I want to format the value and add a html attribute for css class.
If I use @Html.TextBoxFor(m => m.DateModified)
- I can add html attribute but formatting does not work via DisplayFormat attribute on the member.
If I use @Html.EditorFor(m => m.DateModified)
- Formatting works but I cannot add html attribute
If I use @Html.TextBox("DateModified", Model.DateModified, ...)
- I get null reference exception when Model is null when the form is in add mode
What is the best way to achieve this?
The EditorFor() Helper is just like the TextBoxFor() Helper above with the exception that it will actually read metadata and other attributes from the Model to determine the appropriate type of element to render (such a checkbox for a boolean field) and it will map those values accordingly from the Model.
The Html. Editor() or Html. EditorFor() extension methods generate HTML elements based on the data type of the model object's property. The following table list the data types and releted HTML elements: DataType.
I ended up solving this by creating a custom editor template for my date picker as so:
Shared/EditorTemplates/DateTime.cshtml
@model System.DateTime?
@Html.TextBox("", Model.HasValue ? Model.Value.ToString("dd/MM/yyyy") : string.Empty, new { @class = "date-picker" })
Then in my original page continue to use
@Html.EditorFor(m => m.DateModified)
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