【发布时间】:2015-04-23 18:20:10
【问题描述】:
我正在尝试关注 this example 以正确应用日期时间格式
我有包含日期时间属性的视图模型
public class MyViewModel {
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd.MM.yyyy HH:mm:ss}")]
public DateTime Starting { get; set; }
}
内部视图我有表单
@using (Html.BeginForm(null, null, null, FormMethod.Post, new { @id = "myForm", @name = "myForm" }))
{
...
<div class="form-group">
@Html.LabelFor(model => model.Starting, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Starting, new { htmlAttributes = new { @class = "dateTimePicker" } })
@Html.ValidationMessageFor(model => model.Starting, "", new { @class = "text-danger" })
</div>
</div>
}
在同一页面内的脚本部分
<script>
jQuery.validator.addMethod("MyDateTimeFormat", function (value, element) {
return Date.parseExact(value, "dd.MM.yyyy HH:mm:ss");
}, "Please provide correct datetime format!");
var form = $("#myForm");
form.validate({
rules: {
Starting: { MyDateTimeFormat: true }
}
});
$("#myForm").submit(function () {
if (form.valid())
alert("The form is valid: \n" + Date.parse($("#Starting").val()));
$("#Starting").val() = Date.parse($("#Starting").val());
else {
alert("Valid: " + form.valid());
}
});
</script>
日期格式已正确应用,但在控制器内的HttpPost 操作上提交表单后,我得到MyViewModel.Starting 的默认值01/01/0001 不是在视图中选择的那个。我做错了什么?
编辑: 添加到 Global.asax.cs
protected void Application_BeginRequest(Object sender, EventArgs e)
{
string cultureName = CultureHelper.GetImplementedCulture("de-DE");
Thread.CurrentThread.CurrentCulture = new CultureInfo(cultureName);
Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
}
【问题讨论】:
-
这看起来像是文化问题。请确保发送到服务器的数据可以在服务器端进行解析。你应该和 fiddler 一起看看实际传输了什么。在所有情况下,您都应该尝试以中性格式发送信息(即 yyyy-MM-dd HH:mm:ss)
-
你有什么建议?重点是以这种特定格式格式化日期时间。我是否应该在发送之前即时转换为默认格式,如果是这样的话。谢谢
标签: javascript jquery .net asp.net-mvc