0

I've added jQueryUI DatePicker on HtmlTextBoxFor in my MVC application. Below is my code. Now when I debug, The date shows 01/01/2001 12:00:00 in the create event instead of the date selected.

<!-- JoinDate -->
<div class="form-group">
    <div class="editor-label">
        @Html.LabelFor(model => model.JoinDate, new { @class = "col-sm-2 control-label" })
</div>
<div class="editor-field">
    @Html.TextBoxFor(model => model.JoinDate, new { @class = "form-control", @id = "datepicker" })
    @Html.ValidationMessageFor(model => model.JoinDate)
</div>

<script src="~/Content/js/jquery.js"></script>
<script src="~/Scripts/jquery-ui-1.11.4.min.js"></script>

<script>
$(function () {
    $("#datepicker").datepicker();
});

DhavalR
  • 1,409
  • 3
  • 29
  • 57

1 Answers1

0

Well I found a solution to this. I added an input and assign it jQueryUI datepicker. Now onSelect event, it just set the value to the TextBoxfor. See the code below.

<script>
$(function () {
    $("#datepicker").datepicker();
});

<script>
$('#datepicker').datepicker({
    changeMonth: true,
    changeYear: true,
    dateFormat: "dd-mm-yy",
    constrainInput: true,
    defaultDate: new Date(1975, 1 - 1, 1),
    yearRange: "2000:2025",
    onSelect: function () {
        alert($('#datepicker').val());
        $('#joindate').val($('#datepicker').val());
    }
});
</script>

<!-- JoinDate -->
                        <div class="form-group">
                            <div class="editor-label">
                                @Html.LabelFor(model => model.JoinDate, new { @class = "col-sm-2 control-label" })
                            </div>
                            <div class="editor-field">
                                <input type="text" id="datepicker" onchange="onDateChange()"/>
                                @Html.TextBoxFor(model => model.JoinDate, new { @class = "form-control", @id="joindate" })
                                @Html.ValidationMessageFor(model => model.JoinDate)
                            </div>
                        </div>
DhavalR
  • 1,409
  • 3
  • 29
  • 57
  • 1
    There is no reason to use `defaultDate:` - If the value of property `JoinDate` is set in the controller before you pass the model to the view, then that value will be displayed. –  Apr 27 '16 at 03:41
  • Actually this controller is to create. When I use it in View, I would not need `datepicker`. – DhavalR Apr 27 '16 at 03:45
  • That makes no sense. Why are you asking a question about something that's not needed? And why are you using `new { id="joindate" }` - the `id` is already `id="JoinDate"` –  Apr 27 '16 at 03:51
  • Thanks for the second advice. I actually did not know that. For the first thing you said, I know people here don't ask anything that is not needed. I need to implement datepicker for Create controller. In View details, I just show the date in Textboxfor. No need to change it in View. – DhavalR Apr 27 '16 at 04:04