在我的模特中
[DataType(DataType.Date)]
[Display(Name="Event Date")]
[DisplayFormat(DataFormatString = "{0:d}")]
//[DisplayFormat(ApplyFormatInEditMode=true ,DataFormatString="{0:DD/MM/YYYY}")]
public DateTime EventDate { get; set; }
在我的视图(Create.cshtml)
中<div class="editor-label">
@Html.LabelFor(model => model.EventDate)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.EventDate)
@Html.ValidationMessageFor(model => model.EventDate)
</div>
在Shared / EditorTemplates / Date.cshtml中
@model DateTime
@Html.TextBox("", String.Format("{0:d}", Model.ToShortDateString()),
new { @class = "datefield", type = "date" })
并收到以下错误
The model item passed into the dictionary is null, but this dictionary requires a non-null model item of type 'System.DateTime'.
答案 0 :(得分:6)
谢谢解决了....只是把脚本放在文件中..
@model Nullable<DateTime>
@{
DateTime dt = DateTime.Now;
if (Model != null)
{
dt = (System.DateTime)Model;
}
@Html.TextBox("", String.Format("{0:d}", dt.ToShortDateString()), new { @class = "datefield", type = "date" })
}
<script type='text/javascript'>
$(document).ready(function () {
$(".datefield").datepicker({
// buttonImage: "/content/images/calendar.gif",
// showOn: "both",
// defaultDate: $("#calendar-inline").attr('rel')
showAnim: 'slideDown',
dateFormat: 'dd/mm/yy'
});
});
</script>
答案 1 :(得分:3)
尝试将EventDate
定义为可空类型:DateTime?
答案 2 :(得分:2)
您将需要使用DateTime?
作为模型,并直接处理null值。
在可空类型上,您调用.HasValue
以查看该值是否实际为空,或使用??
。这就是我的一些设置代码的工作原理:
// get the date the editor will work with, or use today's date if it is null
DateTime workingDate = if (Model.HasValue) ? Model.Value : DateTime.Now;
// check the model metadata to see if the underlying model type was nullable or not
bool isNullable = ViewData.ModelMetadata.IsNullableValueType;
// get the min date passed in as optional params. default to some reasonable timeframe
var minDate = ViewBag.MinDate ?? DateTime.Now.AddDays(-30)
// now start drawing the editor
This blog post是一个方便的地方,可以开始阅读一些属性。
答案 3 :(得分:0)
虽然这是一个错误的时间问题,但我有另一种方法。您可以在模型上创建构造函数并使用某些值初始化date属性,比如今天的日期。然后在您的操作方法上从控制器创建,您可以将模型的新实例作为返回视图语句的参数传递。