javascript - ASP.NET MVC 中的日期格式设置

标签 javascript jquery asp.net-mvc

我在弄清楚如何格式化我看来的日期时遇到了一些麻烦。在我的应用程序中,我有一个编辑按钮。单击后,文本框即可编辑日期值。然而,它也向我显示了我不想看到的时间。我该如何解决这个问题?

Application

The Problem with the Application

我的模型类中的代码:

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

我的 View 类中的代码:

<td class="Planned_Date">
    <span>@Html.DisplayFor(x=>item.Planned_Date)</span>
    @Html.TextBoxFor(x => item.Planned_Date)
</td>

onClick():

  $("body").on("click", "#tblCustomers .Edit", function () {
            var row = $(this).closest("tr");
            $("td", row).each(function () {
                if ($(this).find("input").length > 0) {
                    $(this).find("input").show();
                    $(this).find("span").hide();
                }
            });
            row.find(".Update").show();
            row.find(".Cancel").show();
            $(this).hide();
        });

最佳答案

您需要编辑模型上的DataAnnotation

[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]

添加ApplyInEditMode属性:

[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}"), ApplyFormatInEditMode = true)]

这将使DataFormartString应用于使用EditorFor或其他编辑器生成的文本框。从这里MSDN article ,

The ApplyFormatInEditMode setting specifies that the specified formatting should also be applied when the value is displayed in a text box for editing. (You might not want that for some fields — for example, for currency values, you might not want the currency symbol in the text box for editing.)

然后,您应该更新 View 以使用 Razor 帮助器 Html.EditorFor,而不是在 View 中声明输入元素并设置模型中的值。引用Microsoft API了解更多信息。

<td class="Planned_Date">
    <span>@Html.DisplayFor(x=>item.Planned_Date)</span>
    @Html.EditorFor(x=>item.Planned_Date)  
</td>

您可能需要调整示例代码以适合您的情况(例如,添加类或样式)。您的 JavaScript 应该仍然可以工作。

注意:DisplayFormat DataAnnotation 不适用于使用 Html.TextboxFor 生成的输入。它仅适用于使用 Html.EditorFor 和 Razor Display 帮助程序生成的文本框(或其他编辑器)。

关于javascript - ASP.NET MVC 中的日期格式设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52767123/

相关文章:

javascript - 为什么在 Safari 中单击/聚焦子文本框时,父元素单击事件会自动触发?

javascript - ng-class 禁用 ng-table header 的 ng-show?

jquery - 如何使用 jquery 禁用按钮

asp.net - 用于跨数据库表的 LINQ to SQL。还是查看?

javascript - Cycle2 - 转到 : skipping

javascript - 正则表达式 JS : Searching between two same words

javascript - 如果在已获得焦点时单击文本输入,如何执行某些操作 - 在 iPhone 上

javascript - 弹出窗口在 Javascript 中不起作用

JavaScript/JQuery 交换 HTML 表格的水平和垂直顺序

asp.net-mvc - 如何在 VisualStudio 2013 RC AccountController.cs 中的 Microsoft.Owin.Security 中创建角色 - API 文档