モデルクラスにタイプタイプのプロパティがあるDateTime場合、どのように特定の形式(たとえば、ToLongDateString()返される形式)でレンダリングできますか?
私はこれを試しました...
@Html.DisplayFor(modelItem => item.MyDateTime.ToLongDateString())
...式はプロパティまたはフィールドを指す必要があるため、例外がスローされます。この...
@{var val = item.MyDateTime.ToLongDateString();
Html.DisplayFor(modelItem => val);
}
...これは例外をスローしませんが、レンダリングされた出力は空です(ただしval、デバッガーで確認できるように、期待値が含まれています)。
事前にヒントをありがとう!
編集する
ToLongDateString例にすぎません。代わりに実際に使用したいのToLongDateStringは、DateTimeおよびのカスタム拡張メソッドですDateTime?。
public static string FormatDateTimeHideMidNight(this DateTime dateTime)
{
if (dateTime.TimeOfDay == TimeSpan.Zero)
return dateTime.ToString("d");
else
return dateTime.ToString("g");
}
public static string FormatDateTimeHideMidNight(this DateTime? dateTime)
{
if (dateTime.HasValue)
return dateTime.Value.FormatDateTimeHideMidNight();
else
return "";
}
そのため、ViewModelプロパティでDisplayFormat属性とDataFormatStringパラメーターを使用できないと思います。