ASP.NET offers a good way to keep your code clean of redundant data, e.g. Bootstrap classes you would have to assign to every visible HTML element again and again.
As a .NET Core MVC sample for single elements, you would write code like
1 |
@Html.TextBoxFor(m => m.StartTime, new { @class = "form-control", @type = "datetime" }) |
Or, if you use tools like the bootstrap-datetimepicker for a comfortable date and time input, there would be even more DIVs:
1 2 3 4 5 6 7 8 |
<div class='input-group date' id='datetimepickerStarttime'> @Html.TextBoxFor(m => m.StartTime, new { @class = "form-control", @type = "datetime" }) <span class="input-group-addon"> <span class="glyphicon glyphicon-calendar"></span> </span> </div> |
How to use templates
You can specify EditorTemplates for certain types or models. The same behavior works e.g. for DisplayTemplates (DisplayFor()). I will explain how to create an EditorTemplate for type DateTime.
First, create a folder and an empty file: \Views\Shared\EditorTemplates\DateTime.cshtml
Paste this code into it:
1 2 3 4 5 6 7 8 |
<div class='input-group date' id='@("datetimepicker"+ViewData.TemplateInfo.HtmlFieldPrefix)'> @Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { @class = "form-control", type = "datetime" }) <span class="input-group-addon"> <span class="glyphicon glyphicon-calendar"></span> </span> </div> |
Afterwards, you can simply write
1 |
@Html.EditorFor(m => m.StartTime) |
into your main cshtml file to get the full template loaded:
For JavaScript/jQuery access, use the value we created in the first line of the template, datetimepicker[yourModelPropertyName], in this case “datetimepickerStartTime”.
Example:
1 |
$('#datetimepickerStartTime').datetimepicker(); |
Comments