Select Page
This entry has been published on 2017-02-11 and may be out of date.

Last Updated on 2017-02-11.

[:en]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

@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:

<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:

<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

@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:

$('#datetimepickerStartTime').datetimepicker();

 

 [:]