[asp.net-mvc] How to add Date Picker Bootstrap 3 on MVC 5 project using the Razor engine?

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>

This question is related to asp.net-mvc twitter-bootstrap razor

The answer is


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

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.


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" })
    

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


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


Simple:

[DataType(DataType.Date)]
Public DateTime Ldate {get;set;}

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

@(Html.ShieldDatePicker()
    .Name("datepicker"))

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(){...});


Examples related to asp.net-mvc

Using Lato fonts in my css (@font-face) Better solution without exluding fields from Binding Vue.js get selected option on @change You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to send json data in POST request using C# VS 2017 Metadata file '.dll could not be found The default XML namespace of the project must be the MSBuild XML namespace How to create roles in ASP.NET Core and assign them to users? The model item passed into the dictionary is of type .. but this dictionary requires a model item of type How to use npm with ASP.NET Core

Examples related to twitter-bootstrap

Bootstrap 4: responsive sidebar menu to top navbar CSS class for pointer cursor How to install popper.js with Bootstrap 4? Change arrow colors in Bootstraps carousel Search input with an icon Bootstrap 4 bootstrap 4 responsive utilities visible / hidden xs sm lg not working bootstrap.min.js:6 Uncaught Error: Bootstrap dropdown require Popper.js Bootstrap 4 - Inline List? Bootstrap 4, how to make a col have a height of 100%? Bootstrap 4: Multilevel Dropdown Inside Navigation

Examples related to razor

Uncaught SyntaxError: Invalid or unexpected token How to pass a value to razor variable from javascript variable? error CS0103: The name ' ' does not exist in the current context how to set radio button checked in edit mode in MVC razor view @Html.DropDownListFor how to set default value Razor MVC Populating Javascript array with Model Array How to add "required" attribute to mvc razor viewmodel text input editor How to correctly use Html.ActionLink with ASP.NET MVC 4 Areas Multiple radio button groups in MVC 4 Razor How to hide a div element depending on Model value? MVC