asp.netasp.net-mvcrazorasp.net-mvc-5

Using Datepicker In Razor Form - ASP.NET MVC


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.


Solution

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