6

在我的模型中

[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'.
4

4 回答 4

7

谢谢解决了....只需将脚本放入文件中..

@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>
于 2012-05-17T09:08:10.183 回答
3

尝试将您定义EventDate为可为空的类型:DateTime?

于 2012-04-29T11:40:08.830 回答
2

您将需要DateTime?用作模型,并直接处理空值。

在可空类型上,您调用.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

这篇博文是开始阅读一些属性的好地方。

于 2012-05-14T06:15:37.673 回答
0

虽然这是一个错误的时间问题,但我有另一种方法。您可以在模型上创建一个构造函数并使用一些值初始化日期属性,比如今天的日期。然后在从控制器创建的操作方法上,您可以将模型的新实例作为参数传递给返回视图语句。

于 2014-05-13T19:44:41.860 回答