Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Html.TextBoxFor formatting or Html.EditorFor htmlAttributes?

Tags:

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?

like image 967
lahsrah Avatar asked May 12 '11 01:05

lahsrah


People also ask

What is the difference between TextBoxFor and EditorFor?

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.

What is HTML EditorFor?

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.


1 Answers

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)
like image 60
lahsrah Avatar answered Sep 19 '22 13:09

lahsrah