我有型号:
const string MyDateFormat = "yyyy-MM-dd";
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = MyDateFormat, ApplyFormatInEditMode = true)]
public DateTime Date { get; set; }
并查看:
@Html.EditorFor(model => model.Date, new { htmlAttributes = new { @class = "form-control datepicker" } })
由于某种原因,在表单加载时没有设置模型值,我想知道为什么?
我必须手动:
<script type="text/javascript">
$(document).ready(function () {
var elem = $("#Date").val('@Model.Date.ToString(MyDateFormat)');
});
</script>
但是,在表单中我看到 dd.MM.yyyy (这是我的计算机区域设置)格式,为什么?
如果尝试设置 MyDateFormat = "dd.MM.yyyy"不起作用,请参阅 dd.MM.yyyy:
据我所知,yyyy-MM-dd是.net运行时本地格式,dd.MM.yyyy是我的计算机本地格式。
如何做到不依赖于计算机的区域设置和 .net 运行时区域设置?
最佳答案
我相信您错过了表达式周围的大括号。
尝试将表达式 yyyy-MM-dd
括在大括号中,如下所示 {0:yyyy-MM-dd}
const string MyDateFormat = "{0:yyyy-MM-dd}";
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = MyDateFormat, ApplyFormatInEditMode = true)]
public DateTime Date { get; set; }
您还可以在 View 中使用以下内容,而不是使用 DisplayFormat
属性来装饰模型属性。
@Html.TextBoxFor(model => model.Date, "{0:yyyy-MM-dd}", new { @class="datePicker"});
关于c# - 为什么日期时间选择器会这样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33585031/