2

I have a page with a datetime input on it, along with the customary JQuery datepicker, and an editor template for "Date" which formats the date in the text box and the date that is passed into the view and adds the required clases etc.

When I call the page from the default action (which takes a nullable datetime for passing the date into), I get a populated date and it formats correctly (in this case dd/mm/yyyy). When I call the page with a datetime, it builds the date correctly in the action, but the page renders the date as "mm/dd/yyy hh:mm:ss", rather than the desired format. The url I'm calling the action with is <url>?reportDate=06%2F13%2F2012%2000%3A00%3A00, which is rendered from an html helper action link, passing in the model date as the parameter, and the action can translate this to the correct date. If I try to call the page with <url>?reportDate=13%2F06%2F2012 (the format I want to display the date as), the action takes it as a null parameter being passed, the page displays the date correctly, but a validation exception is thrown - The value '13/06/2012' is invalid.

I'm in the UK, I've got my globalization in the web.config set to en-GB, but for some reason it's validating against the US version of the date by the looks of it.

Model:

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

    //More code here
}

Template (in Shared\EditorTemplates\Date.spark and using SparkViewEngine):

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

View:

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

Action:

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

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

If I need to provide more detail, please let me know.

Any help greatly appreciated.

4

1 回答 1

1

默认模型绑定器在解析时使用带有 GET 请求的 InvariantCulture 和用于 POST 请求的线程区域性。这基本上意味着如果您reportDate在 GET 请求中传递您的操作参数(作为查询字符串参数),您必须使用 InvariantCulture 对其进行格式化。理想情况下使用:

some_url?reportDate=yyyy-MM-dd

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

查看以下说明这一点的博客文章。

于 2012-06-29T12:43:09.613 回答