Hasan Mir Hasan Mir - 3 months ago 57
ASP.NET (C#) Question

Datepicker not working in asp.net mvc

net MVC this is my razor view of create a Bill which have a property Due Date i want to use date picker in my code but its not working when i use following code:

<div class="form-group">
@Html.LabelFor(model => model.DueDate, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(model => model.DueDate, new { id = "datepicker" })
@Html.ValidationMessageFor(model => model.DueDate)
</div>
</div>
<script type="text/javascript">
$(document).ready(function () { $("#datepicker").datepicker({ });});
</script>


So i changed the code to following then it started working but how can i pass the dudate value to controller the above code automatically attaches the due date value to object but the beelow code cant.

<div class="form-group">
@Html.LabelFor(model => model.DueDate, new { @class = "control-label col-md-2" })
<div class="col-md-10">
<input type="date" id="datepicker" class="form-control"/> //Changing
@Html.ValidationMessageFor(model => model.DueDate)
</div>
</div>
<script type="text/javascript">
$(document).ready(function () { $("#datepicker").datepicker({ });});
</script>


Any Help in any of the above code ASAP Thank You!

Answer

The code in your first snippet uses a date time picker control provided by jQuery UI library.To make it work you need to add a reference to the following files in this order:

  1. jQuery.js
  2. jQueryUI.js
  3. jQueryUI.css

So your final code should look something like this:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.11.1/jquery-ui.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.css" rel="stylesheet">
<script type="text/javascript">
    $(function () {
        $("#datepicker").datepicker();
    });
</script>

The code in your second snippet uses an HTML 5 input of type date, as was pointed out by Stephen.This automaticallly makes the input a date time picker if it's supported by the browser.

The reason the second snippet wasn't working is that the binding in MVC happens on the name property.Since your C# property is called DueDate you need to add name="DueDate" to the input element.

Change this line:

<input type="date" id="datepicker" class="form-control"/> 

To this:

<input name="DueDate" type="date" id="datepicker" class="form-control"/>