【问题标题】:How to add a Date Picker on my View on a MVC project如何在 MVC 项目的视图上添加日期选择器
【发布时间】:2018-06-18 14:53:34
【问题描述】:

我正在学习 .NET MVC,在我的视图上添加日期选择器有点困难。

我想做的是创建名为 Person.cs 的 Model

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

我正在创建一个名为 Create.chstml 的视图,它用于创建新用户。

    @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>
}

有没有最简单的方法来表明它必须弹出一个日期选择器?

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

我已经在数据包块上安装了 JQuery.UI.Combined

做了一些研究,我发现了这个链接: https://jqueryui.com/datepicker/

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

其实我不知道如何在我的代码上实现。

我也在尝试点击此链接:

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

从该视频中找到的解决方案https://www.youtube.com/watch?v=Yuo2XX5_rYo

【问题讨论】:

  • 在初始化 jQuery 插件的那一行再次检查你的 jQuery 选择器是否正确。您是否尝试为具有 Id 属性值 datepicker 的输入启用日期选择器?当您尝试$( "#DateOfBirth" ).datepicker(); 时会发生什么?
  • 我在你的视图中没有看到任何元素 #datepicker
  • 我已经更正了元素:@Html.EditorFor(model => model.DateOfBirth, new { htmlAttributes = new { @class= "form-control datepicker" } }) 我确定,遗漏了一些东西在导入,但不知道在哪里...

标签: asp.net-mvc jquery-ui-datepicker


【解决方案1】:

问题可能是你的 jQuery 选择器:

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

目前这将找到带有id datepicker 的 HTML 元素。查看您的 HTML sn-p,它将使用 id DateOfBirth 生成输入(仔细检查检查元素时的外观)。试试:

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

更好的选择是在您的 HTML 元素中添加一个 datepicker 类(或类似的),然后将其用作选择器,以便它适用于您将来可能希望使用的所有日期选择器:

查看

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

Javascript

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

我还会研究选择器的工作原理,以便您更好地确定如何使用它们,例如,如果它以 # 为前缀,它将查找具有 id 属性的元素。如果它以 . 为前缀,那么它将查找具有您指定的类的所有元素。

【讨论】:

  • 不幸的是无法正常工作:s 正如您在顶部看到的,我安装了插件,添加到 bundle 并添加了 datpicker 脚本。我找到了一种解决方法,它仅适用于某些浏览器: [DataType(DataType.Date)] [DisplayFormat(DataFormatString = "{0:yyyy/MM/dd}", ApplyFormatInEditMode = true)] public DateTime?出生日期 { 得到;放; }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-03
相关资源
最近更新 更多