【问题标题】:MVC4 Html.EditorFor for Date using Twitter Bootstrap使用 Twitter Bootstrap 的 MVC4 Html.EditorFor 日期
【发布时间】:2014-09-09 15:36:48
【问题描述】:

我正在使用 MVC4 Razor 为仅日期字段构建一个输入框。这是我的代码:

    @Html.EditorFor(model => model.StartDate, new { @class = "form-control", type = "text" })

对于StartDate,我有以下定义:

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

发生的情况是该框没有被表单控制格式化,使用纯 HTML 输入样式。

我尝试更改日期的文本,但它不适用于 IE,因为这是不受支持的功能...而且我的应用程序也必须与 IE 一起使用。

我知道 MVC5 在这方面有一些变化,但我不能从项目需求中使用它。应该是 MVC4。

如何使数据输入样式如预期的那样作为表单控件?

【问题讨论】:

    标签: html asp.net-mvc twitter-bootstrap asp.net-mvc-4 razor


    【解决方案1】:

    添加属性只适用于 MVC 5.1,所以你是对的,那是行不通的。您可以在 /Views/Shared 文件夹中添加一个 EditorTemplates 文件夹,并在其中放置一个 DateTime 编辑器,并根据需要定义 HTML 控件。在您的模板中,您可以定义:

    //DateTime.cshtml
    model System.DateTime
    
    @Html.TextBox("", Model.ToShortDateString(), new { @class = "form-control" })
    

    【讨论】:

    【解决方案2】:

    我的解决方案是在 /Views/Shared 中添加一个 EditorTemplate,添加引导日期选择器(来自 here)和以下代码:

    @model DateTime?
    @Html.TextBox("", Model.HasValue ? Model.Value.ToString("d") : String.Empty, new { @class = "form-control" })
    <script type="text/javascript">
        $(function () {
            // target only the input in this editor template
            $('#@Html.IdForModel()').datetimepicker({
                pickTime: false
            });
        });
    </script>
    

    工作正常......使用日期选择器......

    【讨论】:

      猜你喜欢
      • 2012-09-16
      • 2012-01-06
      • 1970-01-01
      • 2013-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-17
      相关资源
      最近更新 更多