0

I am in the initial phase of leaning web app development in MVC and having few questions related to below code -

[Display(Name = "Start Date")]
public DateTime StartDate { get; set; }

<div class="form-group">
    @{ Html.Html5DateRenderingMode = Html5DateRenderingMode.Rfc3339; }
    @Html.LabelFor(emp => emp.StartDate)
    @Html.TextBoxFor(emp => emp.StartDate, new { @class = "form-control" })
    @Html.EditorFor(emp => emp.StartDate, new { htmlAttributes = new { @class = "form-control" } })
</div>

Rendered as

enter image description here

I understand that TextBoxFor is rendered as type="text" and EditorFor as type="datetime"
Questions -

1. Why TextBoxFor and EditorFor displays dates differently - 
   Does Html5DateRenderingMode is only applicable to input type="datetime"?

2. Why controls are rendered differently? I noticed that EditorFor which is rendered as type="datetime" is displayed on full page length input box.

3. When do we use Html5DateRenderingMode in a real-life project?

4. I understand that EditorFor is a preferred approach as it looks at object meta information and decides what control should be rendered.
In what cases, we should prefer TextBoxFor over EditorFor?

Thank you!

Siguza
  • 21,155
  • 6
  • 52
  • 89
inutan
  • 10,558
  • 27
  • 84
  • 126

1 Answers1

1
  1. HTML.TextboxFor will simply call the .ToString() Function on the passed object and display whatever the result is. HTML.EditorFor on the other hand, takes the datatype into account and therefore pays attention to your Html5DateRenderingMode.
  2. To see why both controls are rendered differently, you have to check the css applied to both. You can do this the easiest by rightclicking on of the controls and inspecting them. I would guess, that you have a maximum width specified for input[type=text] but not input[type=datetime] in your css.
  3. I haven't used it yet. If you stick to EditorFor and want to switch your datetime rendering to Rfc3339 I would put it in your custom template as the default value.
  4. TextboxFor is the prefered solution, if you want to get specifically an input of the type text for your property. As shown here: Differences between Html.TextboxFor and Html.EditorFor in MVC and Razor EditorFor can be overwritten to display pretty much anything you want. So, you could write code that displays all your integers as a slider, which might not always be what you want, e.g. for really large numbers that still have to be precise the slider would be hard to work with. Another option would be, if you use libraries which pose a conflict with the elements generated by EditorFor. However, even in that case it would still be possible to stick with EditorFor by using the UIHintAttribute https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.uihintattribute(v=vs.118).aspx
Community
  • 1
  • 1
Arne Klein
  • 662
  • 5
  • 12