asp.net-mvc 如何使用 Razor 引擎在 MVC 5 项目上添加日期选择器 Bootstrap 3?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21104633/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 03:26:10  来源:igfitidea点击:

How to add Date Picker Bootstrap 3 on MVC 5 project using the Razor engine?

asp.net-mvctwitter-bootstraprazor

提问by Ben Junior

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

我需要一些关于如何使用 Razor 引擎在 MVC 5 项目上安装Date PickerBootstrap 3 的指南。我在这里找到了这个链接但无法在 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>

采纳答案by Karhgath

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

这个答案使用jQuery UI Datepicker,它是一个单独的包含。在不包含 jQuery UI 的情况下,还有其他方法可以做到这一点。

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

首先,您只需要将datepicker类添加到文本框,此外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:

然后,为了确保在呈现文本框后触发 javascript,您必须将 datepicker 调用放在 jQuery 就绪函数中:

<script type="text/javascript">
    $(function () { // will trigger when the document is ready
       $('.datepicker').datepicker(); //Initialise any date pickers
    });
</script>

回答by Keagz93

This answer simply applies the type=dateattributeto the HTML inputelement 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.

此答案只是将该type=date属性应用于HTMLinput元素,并依赖浏览器提供日期选择器。请注意,即使在 2017 年,并非所有浏览器都提供自己的日期选择器,因此您可能希望提供一个后备。

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

您所要做的就是向视图模型中的属性添加属性。变量示例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.

假设您使用的是 MVC 5 和 Visual Studio 2013。

回答by Enzero

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.

这个答案使用Bootstrap DatePicker Plugin,它不是 bootstrap 的原生。

Make sure you install Bootstrap DatePicker through NuGet

确保通过 NuGet 安装 Bootstrap DatePicker

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.

创建一小段 JavaScript 并将其命名为 DatePickerReady.js,将其保存在 Scripts 目录中。这将确保它即使在非 HTML5 浏览器中也能正常工作,尽管现在这些浏览器很少。

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.

现在设置数据类型,以便在使用 EditorFor 时 MVC 将识别要使用的内容。

<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

在此处输入图片说明

回答by waqar ahmed

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

在模型中的 datetime 属性之前添加这两行

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

and result will be :Date Picker in MVC Application

结果将是:MVC 应用程序中的日期选择器

回答by stefaleon

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

试图根据Enzero的回答提供简洁的更新。

  • Install the Bootstrap.Datepickerpackage.

    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 datepickerclass 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" })
    
  • 安装Bootstrap.Datepicker包。

    PM> install-package Bootstrap.Datepicker
    ...
    Successfully installed 'Bootstrap.Datepicker 1.7.1' to ...
    
  • AppStart/BundleConfig.cs 中,在 bundle 中添加相关的脚本和样式。

    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"));
    
  • 在相关视图的脚本部分,启用和自定义日期选择器。

    @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>
    
  • 最后在相关控件中添加datepicker类。例如,在 TextBox 和“31/12/2018”之类的日期格式中,这将是:

    @Html.TextBox("YOUR-STRING-FOR-THE-DATE", "{0:dd/MM/yyyy}", new { @class = "datepicker" })
    

回答by dnxit

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

像这样装饰你的模型。可以使用引导日期时间选择器我用过这个。 https://github.com/Eonasdan/bootstrap-datetimepicker/

I suppose you already have bundles for bootstrap css and js

我想你已经有 bootstrap css 和 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

您的 HTML 视图

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

回答by chenZ

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

1.确保首先引用jquery.js
2.检查布局,确保调用“~/bundles/bootstrap”
3.检查布局,请参阅渲染部分脚本位置,它必须在“~/bundles/bootstrap”之后
4 .add class "datepicker" to textbox
5.put $('.datepicker').datepicker(); 在 $(function(){...});

回答by Vladimir Georgiev

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

Checkout Shield UI 的MVC 日期选择器。一个强大的组件,您可以使用以下几行代码集成:

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

回答by GODFATHER

Simple:

简单的:

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