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あなたをnull許容タイプとして定義してみてください:DateTime?

于 2012-04-29T11:40:08.830 に答える
2

DateTime?モデルとして使用し、null 値を直接処理する 必要があります。

null 許容型では、 を呼び出し.HasValueて値が実際に null かどうかを確認するか、 を使用します??。これは私のセットアップコードの一部がどのように機能するかです:

// 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

間違った時間の質問ですが、別のアプローチがあります。モデルにコンストラクターを作成し、今日の日付などのいくつかの値で日付プロパティを初期化できます。次に、コントローラーからアクションメソッドを作成すると、モデルの新しいインスタンスをreturnビューステートメントのパラメーターとして渡すことができます。

于 2014-05-13T19:44:41.860 に答える