我有一个带有datetime输入的页面,还有一个常用的JQuery datepicker,还有一个" date“编辑器模板,用于格式化文本框中的日期和传递到视图中的日期,并添加所需的类等。
当我从默认操作(它接受一个可以为空的datetime来传入日期)调用页面时,我得到一个填充的日期,并且它的格式正确(在本例中是dd/mm/yyyy
)。当我使用datetime调用页面时,它在操作中正确地构建了日期,但是页面将日期呈现为"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);
}
如果我需要提供更多细节,请让我知道。
非常感谢您的帮助。
发布于 2012-06-29 20:43:10
默认的模型绑定器在解析时对GET请求使用InvariantCulture,对POST请求使用线程区域性。这基本上意味着,如果要在GET请求中传递reportDate
操作参数(作为查询字符串参数),则必须使用InvariantCulture对其进行格式化。理想情况下使用:
some_url?reportDate=yyyy-MM-dd
如果您正在发送POST请求(也称为提交包含输入字段的表单),则日期必须根据您的应用程序文化进行格式化,因为这是模型绑定器将使用的。
查看说明这一点的following blog post。
https://stackoverflow.com/questions/11261965
复制相似问题