2012-04-10 104 views
0

考虑以下型号:设置日期时间格式的UpdateModel

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

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

    ... 

随着各自的观点:

<script type="text/javascript"> 
    $(document).ready(function() { 
     $(".datepicker").datepicker({ dateFormat: 'dd/mm/yy' }); // this is the datepicker equivalent to dd/MM/yyyy 
    }); 
</script> 

... 

<% using (Html.BeginForm(FormMethod.Post)) {%> 
    ... 
    <%: Html.TextBox("StartDate", Model.StartDate, new { @class = "datepicker" })%><br /> 
    <%: Html.TextBox("EndDate", Model.EndDate, new { @class = "datepicker" })%> 

    <input type="submit" class="buttonLink" name="submitButton" value="<%: Html.Resource("Preview") %>" /> 

有没有什么好的理由时,就开始日期文本框的数据是2012年2月4日,UpdateModel()将StartDate设置为2012年2月4日,而不是2012年4月2日?

回答

1

这取决于进行输入解析的计算机的文化设置。因此,如果网络服务器设置为基于en-US文化解析DateTime,则即使网页设置为将其渲染为dd/MM/yyyy,它也会将其解析为MM/dd/yyyy。如果您想强制解析始终为一种格式,那么当您在自定义联编程序中调用DateTime.Parse时,必须传入Culture信息。

编辑:其实我觉得这可以在web.config使用默认文化为应用程序设置。虽然我不知道如何做到这一点,但没有与不同的文化背景合作。

MSDN对全球化,将与MVC工作ASP.NET应用程序的好文章。 StackOverflow上的this article也会解释如何在web.config中使用MVC来完成它。如果您按照答案那里它应该自动分析您寻找的格式的日期时间。

+0

你可以发表一个样本,我该如何告诉UpdateModel我想使用的文化? – dcarneiro 2012-04-10 16:31:57

1

2/4/2012是美国英语文化的标准日期时间格式。这意味着2月4日2012年为英国英语文化的相同日期时间格式意味着4月2日2012年

这听起来像你的当前UI区域性设置为en-US,而不是EN-UK。您可以通过检查System.Globalization.CultureInfo.CurrentUICulture进行检查。

+0

但我将我的模型上的日期格式设置为dd/MM/yyyy。为什么UpdateModel仍然使用美国格式? – dcarneiro 2012-04-10 16:30:04

+0

Adam Gritt殴打我,回答了这个问题。 – danludwig 2012-04-10 16:31:28