2

I have a datepicker that I like and that works. It displays as a neat box in line with the rest of my form and clicking the box prompts a datepicker component, where when a date is selected, a text box is populated.

Markup:

<div class="form-group">
    <div id="datepicker-group" class="input-group date" data-date-format="dd/mm/yyyy">
        <input class="form-control" name="data" type="text" />
        <span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>
    </div>
</div>

JQuery

 <script>    
        $(document).ready(function() {
            $("#datepicker-group").datepicker({
                format: "dd-M-yyyy",
                todayHighlight: true,
                autoclose: true,
                clearBtn: true
            });
        });
 </script> 

I also have a form I'm building using @Html.BeginForm and the other properties in my model are assigned their values through @Html.TextBoxFor and free text fields which is simple enough. How do I work this datepicker div into a form field that can be assigned to my StartDate property? I'd like to retain the look & feel of the current datepicker box in addition to the functionality of being able to click the box and the datepicker component pops up.

3
  • Have you looked at stackoverflow.com/questions/2924610/… Commented Jul 29, 2020 at 20:15
  • I have but I can't get it to work. I've implemented a fix of sorts now by using a TextBoxFor with htmlAttribute @type="date" and this works but is a different datepicker with lesser functionality. Commented Jul 29, 2020 at 20:37
  • What you are trying to do is achievable. I think you should edit your question to include examples of the razor for your other text fields. This will help us suggest what you need for this. Commented Jul 29, 2020 at 20:45

3 Answers 3

7

In Razor you can also do:

<input asp-for="StartDate" type="date" class="form-control" />

type can be:

  • date
  • datetime
  • datetime-local
1
  • 1
    Once again, amazed at how easy things are (and how complicated searching for ".NET" anything can be). Thanks! Commented Nov 29, 2023 at 1:20
3

Can you not just do this

<div class="form-group">
    <div id="datepicker-group" class="input-group date" data-date-format="dd/mm/yyyy">
        @Html.TextBoxFor(x => x.StartDate, new {@class="form-control" })         
        <span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>
    </div>
</div>
1

In Razor (dotnet core 8) you can also do:

@Html.EditorFor(model => model.Date, new { htmlAttributes = new { @class = "form-control", type = "date" } })

type can be:

date, datetime, datetime-local

Not the answer you're looking for? Browse other questions tagged or ask your own question.