82

I need some guide lines on how to install a Date Picker Bootstrap 3 on a MVC 5 project using the Razor engine. I found this link here but couldn't make it work in VS2013.

Copying from the example in the later link above I've already done the following:

            bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                  "~/Scripts/bootstrap.js",
                  "~/Scripts/bootstrap-datepicker.js",    // ** NEW for Bootstrap Datepicker
                  "~/Scripts/respond.js"));

        bundles.Add(new StyleBundle("~/Content/css").Include(
                  "~/Content/bootstrap.css",
                  "~/Content/bootstrap-datepicker.css",  // ** NEW for Bootstrap Datepicker
                  "~/Content/site.css"));

Then I've added the script to the index view as follow

@section Scripts {
@Scripts.Render("~/bundles/jqueryval")

<script type="text/javascript">
    $('.datepicker').datepicker(); //Initialise any date pickers
</script>
}

Now, how to call the date picker here?

   <div class="form-group input-group-sm">
    @Html.LabelFor(model => model.DropOffDate)
    @Html.TextBoxFor(model => model.DropOffDate, new { @class = "form-control", placeholder = "Enter Drop-off date here..." })
    @Html.ValidationMessageFor(model => model.DropOffDate)
</div>
Dhaust
  • 5,470
  • 9
  • 54
  • 80
Ben Junior
  • 2,449
  • 10
  • 34
  • 51

10 Answers10

83

This answer uses the jQuery UI Datepicker, which is a separate include. There are other ways to do this without including jQuery UI.

First, you simply need to add the datepicker class to the textbox, in addition to form-control:

<div class="form-group input-group-sm">
    @Html.LabelFor(model => model.DropOffDate)
    @Html.TextBoxFor(model => model.DropOffDate, new { @class = "form-control datepicker", placeholder = "Enter Drop-off date here..." })
    @Html.ValidationMessageFor(model => model.DropOffDate)
</div>

Then, to be sure the javascript is triggered after the textbox is rendered, you have to put the datepicker call in the jQuery ready function:

<script type="text/javascript">
    $(function () { // will trigger when the document is ready
       $('.datepicker').datepicker(); //Initialise any date pickers
    });
</script>
Jess
  • 23,901
  • 21
  • 124
  • 145
Karhgath
  • 1,809
  • 15
  • 11
  • 4
    Yeah this is exactly how I have my code right now and it's not working – Eric Bishard Jan 14 '14 at 03:02
  • 1
    This is why I use Foundation! I have the same thing you do, I tried '@class = "form-control datepicker"' & '@class = "datepicker form-control"' and no dice – Eric Bishard Jan 14 '14 at 03:07
  • 3
    If, by any chance, you are calling it in a partial view, the script must be in the Index page or it won't work if it is the partial view. This was also one of the problems fixed – Ben Junior Jan 14 '14 at 22:27
  • Can I automate Razor so that if there `[DataType(DataType.Date)]` is defined on a field it should automatically add the `datepicker` css class and run the js? – Shimmy Weitzhandler Mar 15 '15 at 03:22
  • When using JS/JQ within Partial Views, I've found using [Forloop HtmlHelpers](https://bitbucket.org/forloop/forloop-htmlhelpers/wiki/Home) really helpful. It makes it a lot easier to compartmentalise scripts within EditorTemplates and DisplayTemplates, aswell as in standard Partial Views. It's not perfect in every scenario, but I've found it helped solve a lot of issues similar to this one. – Apache Mar 20 '15 at 20:06
  • 1
    The MVC 5 templates I have in Visual Studio 2015 don't include JQuery UI so I'm pretty sure you have to install and reference that first before this will work. There's a decent discussion here with links to related tutorials: https://forums.asp.net/t/1975676.aspx?Tutorial+for+Adding+Datepicker+in+MVC+5 – Paul Angelno Mar 22 '17 at 19:49
  • Same a @EricB here. This just dosn't work from the go. Why did razor not have any datepicker in it's Html object ? Why modern browser like firefox and edge dosn't support a simple .... – Antoine Pelletier May 01 '17 at 17:32
  • Chrome supports but it's garbage. Picking a date is a complicated UI so its better done by a library. – Alan Baljeu Jan 23 '20 at 16:54
  • new { htmlAttributes = new { @class = "form-control datepicker", placeholder = "Enter Drop-off date here..." } } – Juvil Jul 27 '20 at 00:19
62

This answer simply applies the type=date attribute to the HTML input element and relies on the browser to supply a date picker. Note that even in 2017, not all browsers provide their own date picker, so you may want to provide a fall back.

All you have to do is add attributes to the property in the view model. Example for variable Ldate:

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

Assuming you're using MVC 5 and Visual Studio 2013.

Jess
  • 23,901
  • 21
  • 124
  • 145
Keagz93
  • 714
  • 5
  • 9
  • 3
    This is THE BEST answer! Is there any way to pick the time and date? `[DataType(DataType.DateTime)] public DateTime BirthDate { get; set; }` didn't work for me. – Yoda Sep 10 '14 at 12:17
  • 2
    The simplest solution is here – 0xh8h Oct 26 '14 at 14:06
  • 27
    That is NOT the correct answer! That solution will only enable browser specific calendars appear on the browser for date fields. That has nothing to do with Bootstrap Datetime plugin. – ilter Oct 28 '14 at 08:55
  • Is there a way i could use this for month selection. A normal text box in bootstrap type="month". How to do this with data annotations? – guitarlass Aug 27 '15 at 11:15
  • Great answer. Yeah it has nothing to do with bootstrap, because why bother with bootstrap when you can append this to your data type. – Scuba Steve Dec 13 '16 at 02:36
  • 3
    This will not working with IE 11 and FF 38. Only Chrome will pick this up. – TheKingPinMirza Feb 08 '17 at 07:36
  • 1
    The other issue with this solution is that when editing the date field, I just see "mm/dd/yyyy" instead of the date value that already exists. – Paul Angelno Mar 22 '17 at 18:40
  • 1
    Pfff, chrome only solution, until every browser has it's own datepicker – Antoine Pelletier May 01 '17 at 18:02
  • What goes in the View? `@Html.DisplayFor(model => model.DateFrom)` just shows the date as a string. Using Chrome btw – Percy Dec 27 '18 at 13:48
  • Got it - `@Html.EditorFor(model => model.DateFrom)` – Percy Dec 27 '18 at 13:55
20

Add just these two lines before the datetime property in your model

[DataType(DataType.Date)] 
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]

and result will be :Date Picker in MVC Application

Owen Pauling
  • 11,349
  • 20
  • 53
  • 64
waqar ahmed
  • 335
  • 2
  • 6
19

I hope this can help someone who was faced with my same problem.

This answer uses the Bootstrap DatePicker Plugin, which is not native to bootstrap.

Make sure you install Bootstrap DatePicker through NuGet

Create a small piece of JavaScript and name it DatePickerReady.js save it in Scripts dir. This will make sure it works even in non HTML5 browsers although those are few nowadays.

if (!Modernizr.inputtypes.date) {
    $(function () {

       $(".datecontrol").datepicker();

    });
}

Set the bundles

bundles.Add(New ScriptBundle("~/bundles/bootstrap").Include(
              "~/Scripts/bootstrap.js",
              "~/Scripts/bootstrap-datepicker.js",
              "~/Scripts/DatePickerReady.js",
              "~/Scripts/respond.js"))

bundles.Add(New StyleBundle("~/Content/css").Include(
              "~/Content/bootstrap.css",
              "~/Content/bootstrap-datepicker3.css",
              "~/Content/site.css"))

Now set the Datatype so that when EditorFor is used MVC will identify what is to be used.

<Required>
<DataType(DataType.Date)>
Public Property DOB As DateTime? = Nothing

Your view code should be

@Html.EditorFor(Function(model) model.DOB, New With {.htmlAttributes = New With {.class = "form-control datecontrol", .PlaceHolder = "Enter Date of Birth"}})

and voila

enter image description here

Jess
  • 23,901
  • 21
  • 124
  • 145
Enzero
  • 1,141
  • 2
  • 17
  • 36
  • 1
    P.S. - Set the bundles in BundleConfig.cs file in App_Start folder. – Amit Mar 17 '16 at 21:45
  • Where do you update the part that reads Public Property DOB As DateTime? = Nothing – Alan Nov 19 '16 at 13:50
  • This appears to be VB.NET, for those tearing their hair out. Tried to convert it to c# but no matter what I tried it did nothing. – SteveCav Aug 14 '17 at 22:52
  • This seems like a good idea, but too many details to replicate your solution. For example, I don't have a Scripts folder, nor a Bundles folder, which your code apparently expects to be filled with certain scripts? – Alan Baljeu Jan 23 '20 at 17:09
8

Attempting to provide a concise update, based on Enzero's answer.

  • Install the Bootstrap.Datepicker package.

    PM> install-package Bootstrap.Datepicker
    ...
    Successfully installed 'Bootstrap.Datepicker 1.7.1' to ...
    
  • In AppStart/BundleConfig.cs, add the related scripts and styles in the bundles.

    bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
          //...,
          "~/Scripts/bootstrap-datepicker.js",
          "~/Scripts/locales/bootstrap-datepicker.YOUR-LOCALE-CODE-HERE.min.js"));
    
    bundles.Add(new StyleBundle("~/Content/css").Include(
          ...,
          "~/Content/bootstrap-datepicker3.css"));
    
  • In the related view, in the scripts' section, enable and customize datepicker.

    @section scripts{
        <script type="text/javascript">
            //...
            $('.datepicker').datepicker({
                format: 'dd/mm/yyyy', //choose the date format you prefer
                language: "YOUR-LOCALE-CODE-HERE",
                orientation: 'left bottom'
            });
        </script>
    
  • Eventually add the datepicker class in the related control. For instance, in a TextBox and for a date format in the like of "31/12/2018" this would be:

    @Html.TextBox("YOUR-STRING-FOR-THE-DATE", "{0:dd/MM/yyyy}", new { @class = "datepicker" })
    
stefaleon
  • 91
  • 1
  • 10
4
[DataType(DataType.Date)]
public DateTime BirthDate { get; set; }

decorate your model like this. can use a bootstrap date time picker I used this one. https://github.com/Eonasdan/bootstrap-datetimepicker/

I suppose you already have bundles for bootstrap css and js

Your date picker bundle entries

 bundles.Add(new ScriptBundle("~/bundles/datePicker").Include(
           "~/Scripts/moment.min.js",
           "~/Scripts/bootstrap-datetimepicker.min.js"));

        bundles.Add(new StyleBundle("~/Content/datepicker").Include(
                 "~/Content/bootstrap-datetimepicker.min.css"));

Render bundles on your Layout View

@Styles.Render("~/Content/datepicker")
@Scripts.Render("~/bundles/datePicker")

Your HTML in view

<div class="form-group">
        @Html.LabelFor(model => model.BirthDate, htmlAttributes: new { @class = "lead col-md-2" })
        <div class="col-md-10">
            @Html.TextBoxFor(model => model.BirthDate, new { @class = "datetimepicker form-control" })
            @Html.ValidationMessageFor(model => model.BirthDate, "", new { @class = "text-danger" })
        </div>
</div>

At the end of your view add this.

<script>
    $(document).ready(function () {
        $('.datetimepicker').datetimepicker({
            format: 'lll'
        });
    });
</script>
dnxit
  • 7,118
  • 2
  • 30
  • 34
  • 1
    Please consider that the input type "date" (set by Datatype.Date) is only supported by Chrome, Safari and Opera right now (as you can see here: http://www.w3schools.com/html/html_form_input_types.asp). – flumingo Dec 07 '15 at 14:32
  • 1
    @leiseliesel I've updated the answer with usage of a bootstrap date time picker. – dnxit Dec 07 '15 at 21:11
3

1.make sure you ref jquery.js at first
2.check layout,make sure you call "~/bundles/bootstrap"
3.check layout,see render section Scripts position,it must be after "~/bundles/bootstrap"
4.add class "datepicker" to textbox
5.put $('.datepicker').datepicker(); in $(function(){...});

chenZ
  • 920
  • 4
  • 16
1

Add @type = "date" on your code :

{ @class = "form-control", placeholder = "Enter Drop-off date here...", @type = "date" }
Kevin M. Mansour
  • 2,915
  • 6
  • 18
  • 35
-1

Checkout Shield UI's Date Picker for MVC. A powerful component that you can integrate with a few lines like:

@(Html.ShieldDatePicker()
    .Name("datepicker"))
Vladimir Georgiev
  • 1,949
  • 23
  • 26
-2

Simple:

[DataType(DataType.Date)]
Public DateTime Ldate {get;set;}
GODFATHER
  • 1
  • 3