1

I am learning .NET MVC, I am having a bit of difficult on adding a Date Picker on my Views.

What I am trying to do is that I want to create my Model called Person.cs:

public class Person
{
    public int Id { get; set; }

    [Required(ErrorMessage = "First name is required")]
    public string FirstName { get; set; }
    public string LastName { get; set; }

    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
    public DateTime? DateOfBirth { get; set; }
}

_Layout.cshtml

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @using System.Web.Optimization
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li>@Html.ActionLink("List", "ListPerson", "Person")</li>
                </ul>
            </div>
        </div>
    </div>

    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/jqueryval")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)
</body>
</html>

BundleConfig.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Optimization;

namespace WebApplication1.App_Start
{
    public class BundleConfig
    {

        // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));

            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.validate*"));

            // Use the development version of Modernizr to develop with and learn from. Then, when you're
            // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
            bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                        "~/Scripts/modernizr-*"));

            bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                      "~/Scripts/bootstrap.js",
                      "~/Scripts/respond.js"));

            bundles.Add(new StyleBundle("~/Content/css").Include(
                      "~/Content/bootstrap.css",
                      "~/Content/site.css"));
        }
    }
}

I am creating a View called Create.chstml, which it consist to create a new user.

    @model WebApplication1.Models.Person

    @{
        ViewBag.Title = "Create";
    }

    <h2>Create</h2> 

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Person</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.FirstName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" })
            </div>
        </div>

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

        <div class="form-group">
            @Html.LabelFor(model => model.DateOfBirth, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.DateOfBirth, new { htmlAttributes = new { @class = "datepicker form-control" } })
                @Html.ValidationMessageFor(model => model.DateOfBirth, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "ListPerson")
</div>

<link href="~/Content/themes/base/jquery-ui.min.css" rel="stylesheet" />

@section Scripts {
    <script src="~/Scripts/jquery-ui-1.12.1.min.js"></script>
    @Scripts.Render("~/bundles/jqueryval")

    <script>
        $(function() {
            $(".datepicker").datepicker(
                {
                    dateFormat: "yy/mm/dd",
                    changeMonth: true,
                    changeYear : true
                });
        });
    </script>
}

Is there any simplest way to indicate on that it must popup a date-picker?

@Html.EditorFor(model => model.DateOfBirth, new { htmlAttributes = new { @class = "form-control datepicker" } })

I have installed on the packet-nugget the JQuery.UI.Combined

Making some research I found this link: https://jqueryui.com/datepicker/

<script>
  $( function() {
    $( "#datepicker" ).datepicker();
  } );
</script>
<p>Date: <input type="text" id="datepicker"></p>

Actually I don't know how to implement on my code.

I am trying to follow this link also:

https://forums.asp.net/t/2134739.aspx?How+to+add+datepicker+to+EditorFor+field+in+asp+net+mvc+5

Solution found from this video: https://www.youtube.com/watch?v=Yuo2XX5_rYo

newbreaker12
  • 87
  • 1
  • 3
  • 12
  • 1
    Double check your jQuery selector is correct on the line which initialize the jQuery plugin. Are you trying to enable datepicker for the input with Id attribute value `datepicker` ? What happens when you try `$( "#DateOfBirth" ).datepicker();` ? – Shyju Jun 18 '18 at 14:54
  • I don't see any element `#datepicker` in your view. – Eric Jun 18 '18 at 16:40
  • I have corrected the element: @Html.EditorFor(model => model.DateOfBirth, new { htmlAttributes = new { @class = "form-control datepicker" } }) I am sure, missing something on the import, but don't know where... – newbreaker12 Jun 19 '18 at 12:49

1 Answers1

1

The issue is probably your jQuery selector:

$("#datepicker").datepicker();

Currently this will find the HTML element with the id datepicker. Looking at your HTML snippet, it will generate the input with the id DateOfBirth instead (double check what it looks like when you inspect element). Try:

$("#DateOfBirth").datepicker();

The better alternative would be to add a class datepicker (or similar) to your HTML element, then use that as the selector so it applies to all datepickers that you may wish to use in the future:

View

@Html.EditorFor(model => model.DateOfBirth, new { htmlAttributes = new { @class = "form-control datepicker" } })

Javascript

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

I'd also look into how selectors work so you can better identify how to use them, for example if it's prefixed with # it will look for an element with that id attribute. If it's prefixed with . then it will look for all elements that have the class you specify.

ediblecode
  • 11,701
  • 19
  • 68
  • 116
  • Unfortunately is not working :s As you can see on top, I installed the plugin, addedd on bundle and addedd the datpicker script. I found a workaround, which work only on some browsers: [DataType(DataType.Date)] [DisplayFormat(DataFormatString = "{0:yyyy/MM/dd}", ApplyFormatInEditMode = true)] public DateTime? DateOfBirth { get; set; } – newbreaker12 Jun 19 '18 at 13:49