0

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.

Szczepan
  • 365
  • 1
  • 6
  • 19
  • Possible duplicate of [Custom EditorTemplate not being used in MVC4 for DataType.Date](http://stackoverflow.com/questions/13925127/custom-editortemplate-not-being-used-in-mvc4-for-datatype-date) – Tieson T. Feb 16 '16 at 07:50
  • It is not a duplicate to Custom Editor Template. This is a separate question about Scaffolding. It could be solved by another way around the problem (Custom Editor Template) which is not the answer – Amir Feb 27 '16 at 23:42

1 Answers1

1

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/

RoLYroLLs
  • 3,113
  • 4
  • 38
  • 57
Amir
  • 1,722
  • 22
  • 20