DateTime编辑器模板不以正确的格式呈现日期

时间:2012-06-29 12:40:33

标签: c# jquery asp.net-mvc-3 spark-view-engine

我有一个带有日期时间输入的页面,以及常规的JQuery日期选择器,以及一个“日期”的编辑器模板,它格式化文本框中的日期和传递到视图中的日期并添加所需的日期clases等。

当我从默认操作调用页面时(将日期传递给可用的日期时间),我得到一个填充日期并且格式正确(在这种情况下为dd/mm/yyyy)。当我使用日期时间调用页面时,它会在操作中正确构建日期,但页面将日期呈现为"mm/dd/yyy hh:mm:ss",而不是所需的格式。我正在调用操作的URL是<url>?reportDate=06%2F13%2F2012%2000%3A00%3A00,它是从html帮助程序操作链接呈现的,将模型日期作为参数传递,操作可以将其转换为正确的日期。如果我尝试使用<url>?reportDate=13%2F06%2F2012(我想要显示日期的格式)调用页面,则操作将其作为传递的空参数,页面正确显示日期,但抛出验证异常 - The value '13/06/2012' is invalid.

我在英国,我在web.config中将我的全球化设置为en-GB,但出于某种原因,它通过它的外观验证了美国版本的日期。

型号:

public class ReportModel
{
    [Required]
    DataType(DataType.Date)]
    public DateTime ReportDate { get; set; }
    public string Message { get; set; }

    //More code here
}

模板(在Shared \ EditorTemplates \ Date.spark中并使用SparkViewEngine):

<viewdata model="DateTime" />
${Html.TextBox("", string.Format("{0:d}", Model.ToShortDateString()), new { id = "", @class = "datepicker" })}

查看:

<p>
    <label for="ProcessDate">
        Date
        <small>
            <span class="error">${Html.ValidationMessageFor(m => m.ReportDate)}</span>
        </small>
    </label>
    ${Html.EditorFor(m => m.ReportDate, "Date")}
</p>

动作:

public ActionResult StatementsReport(DateTime? reportDate)
{
    if (!reportDate.HasValue)
        reportDate = DateTime.Now;

    var report = new ReportModel { ReportDate = reportDate.Value.Date };
    return View("Statements/GenerateReport", report);
}

如果我需要提供更多详细信息,请告知我们。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

默认模型绑定器在解析时使用InvariantCulture和GET请求以及POST请求的线程文化。这基本上意味着如果您在GET请求中传递reportDate动作参数(作为查询字符串参数),则必须使用InvariantCulture来格式化它。理想情况下使用:

some_url?reportDate=yyyy-MM-dd

如果您要发送POST请求(a.k.a提交包含输入字段的表单),则必须根据您的应用程序文化格式化日期,因为这是模型绑定器将使用的。

结帐following blog post,说明了这一点。