JavaScript 和 C# 模型之间的日期格式不一致

本文关键字:日期 格式 不一致 之间 模型 JavaScript | 更新日期: 2023-09-27 18:35:18

**UPDATE

刚刚意识到,除非我使用 Firefox,否则日期在发布过程中根本没有数据绑定。

为什么浏览器会影响服务器端的数据绑定?

我觉得我在吃疯狂的药丸


我的问题是我有一个 JQuery 日期选择器,它似乎以正确的方式(mm/dd/yyyy)格式化,但是当值发布到服务器时,月份和日期会切换。

date 属性像这样添加到页面中(它是隐藏的,以便它可以在发布期间绑定。如果是一个简单的文本框,问题是一样的):

<input type="hidden" name="SearchByDate" id="SearchByDate" value="<%: ((DateTime)Model.SearchByDate).ToString(Web.Common.Config.GetDateFormatBase) %>" />

在我的视图模型中,我指定日期格式如下:

    [DisplayFormat(DataFormatString = Common.Config.GetDateFormat, 
        ApplyFormatInEditMode = true)]
    public DateTime? SearchByDate { get; set; }

我的javascript日期选择器的格式是这样的:

        $("#appointmentDateDiv").datepicker({
------>     dateFormat: "<%= Web.Common.Config.GetDateFormatJavascript %>",
            changeMonth: true,
            onSelect: function (dateText, inst) {
                $("#SearchByDate").val(dateText);
                $("form").submit();
            }
        });

我实际上将格式划分为一个公共类,如下所示:

public const string GetDateFormatBase = @"MM/dd/yyyy";
public const string GetDateFormat = @"{0:" + GetDateFormatBase + "}"; //This is for annotations
public const string GetDateFormatJavascript = "mm/dd/yy";

如您所见,格式都是 sam:月日年。当我第一次加载这样的页面时,一切看起来都很好,因此日期选择器允许我选择正确格式的日期。然后我发布,如果我逐步完成我的代码,一切看起来仍然很好。我什至重新格式化日期以确保在返回视图之前。但是月份和日期总是被切换。

最奇怪的是,在Firefox中,一切都可以正常工作。它在IE,Chrome和Opera中失败。但我不明白为什么...

JavaScript 和 C# 模型之间的日期格式不一致

谢谢,帮助你们。

@JohnKoerner,你是对的,这是一个 l18n 问题。我的 Firefox 设置为 en-US,我的其他浏览器设置为 en-CA。 我不认为它们是不同的日期格式,但它们是。 这在模型绑定期间导致了问题。我的解决方案是使用固定区域性来分析自定义模型绑定器中的所有日期。我从这里得到了这个想法。

但是,我已经使用了与这里不同的模型活页夹。我像这样修改了相关的代码段

retVal = (Nullable<T>)value.ConvertTo(typeof(T), CultureInfo.InvariantCulture);

其中 T 是正在解析的日期时间。

另一件事是确保为日期时间和日期时间注册自定义模型绑定器? 像这样:

ModelBinders.Binders.Add(typeof(DateTime), new DateTimeModelBinder());
ModelBinders.Binders.Add(typeof(DateTime?), new DateTimeModelBinder());

您可以在隐藏字段中使用 String.Format:

<input type="hidden" name="SearchByDate" id="SearchByDate" value="<%:
String.Format("{0:MM/dd/yyyy}",Model.SearchByDate) %>" />