Search code examples
c#asp.nettwitter-bootstrapt4scaffolding

Bootstrap datetimepicker with asp .net scaffolding


I have simple model class with DateTime property.

    [Required]
    [DataType(DataType.DateTime)]
    public DateTime When { get; set; }

Currently Visual Studio Scaffolding generate this:

    <div class="form-group">
        @Html.LabelFor(model => model.When, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.When, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.When, "", new { @class = "text-danger" })
        </div>
    </div>

It's a simple text box. I want to override default scaffolding. I can add something to default templates and my changes are generated.

How to configure i.e. Create.cs.t4 file to generate bootstrap datetimepicker?

There is an if condition to check when this is a enum

else if (property.IsEnum && !property.IsEnumFlags) 

or bool type

bool isCheckbox = property.TypeName.Equals(boolType);

My solution is to add if statement to check whether it's a datetime and generate my own input field. I checked web but it's not a common topic.


Solution

  • If you want to change scaffolding you need to do this:

    bool isDateTime = property.TypeName.Equals("System.DateTime");
    

    In order to check the data type of property you need to check the TypeName. The TypeName takes the string value of the data type and you need to include the name space. e.g. System.Int32, System.DateTime, System.Bool

    You can write the html tags or create your own html helper and and then do something like this:

    <# if (isDateTime) {#>
            @Html.CutomeDateHelperFor(modelItem => <#= "item." + GetValueExpression(property) #>)
     <# } #>
    

    Beside scaffolding, another easier solution is to use Editor Templates. You will create Editor Template for DateTime type and all editorfor tags will be translated to your custom html tags that includes Booststap Date and time picker or anything else like jquery ui calender.

    See this one as an example: https://www.simple-talk.com/dotnet/asp.net/extending-editor-templates-for-asp.net-mvc/