shivani
shivani

Reputation: 1028

Date is not set in DateTime Picker in Asp.net MVC

I have one edit form, On-grid click, all value assign to relative fields, I have one field that is DOB, and I try to assign DOB in datepicker, but DOB do not assign in datepicker & where I am going to wrong that I am not able to understand

I am working with Asp.net MVC using c#

Scripts

<script type="text/javascript" src='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/js/bootstrap.min.js'></script>
<link rel="stylesheet" href='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/css/bootstrap.min.css'
      media="screen"/>
<!-- Bootstrap -->
<!-- Bootstrap DatePicker -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/css/bootstrap-datepicker.css"type="text/css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.js"type="text/javascript"></script>

Code

<div class="row">
    <div class="form-group">
        @Html.LabelFor(model => model.DOB)
        @Html.TextBoxFor(model => model.DOB, new { @class = "form-control", @autocomplete = "off", @id = "SelectedDate" })
    </div>
</div>

JavaScript

 $(function () {
    $("#SelectedDate").datepicker({ dateFormat: 'dd/mm/yy' });
});

enter image description here

Please let me know.

Upvotes: 3

Views: 3123

Answers (1)

shivani
shivani

Reputation: 1028

Change in html that is

Code

<div class="form-group">
        @Html.LabelFor(model => model.DOB)                                       
        @Html.EditorFor(model => model.DOB, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.DOB, "", new { @class = "text-danger" })
     </div>

Model

    [DisplayName("Birth Date")]
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
    public DateTime DOB { get; set; }

To display the date using the default chrome datepicker you need two attributes on your model:

  1. [DataType(DataType.Date)] results in
  2. [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]. The format yyyy-MM-dd is required for the chrome date picker

Thank you

Upvotes: 6

Related Questions