ScottGuのRazorの投稿で指定されているように、宣言型のHTMLヘルパーを作成しようとしていますが、あまり運がありません。DateTimeHelperを含むHelpers.cshtmlファイルをViews/Helpersに配置しようとしましたが、それが取得されないため、MVC3Betaの投稿に従ってApp_Codeで試行しました。今ではそれを取得しますが、次のようなファイルで使用しようとすると、次のようになります。
@DateTimeHelper(DateTime.Now)
コンパイラは、DateTimeHelperが存在しないと文句を言います。
奇妙なことに、ファイルの名前をDateTime.cshtmlに変更すると、ヘルパーの特定のコードに関するエラーなど、別のエラーが発生します。
完全を期すために、ヘルパーのコードは次のとおりです。
@helper DateTimeHelper(DateTime t, bool longDate = true, bool showTime = true, bool longTime = true) {
<time datetime='@t.ToUniversalTime()'>
@if(longDate) {
if(showTime) {
if(longTime) {
@t.ToLongDateString() @t.ToLongTimeString();
} else {
@t.ToLongDateString() @t.ToShortTimeString();
}
} else {
@t.ToLongDateString()
}
} else {
if(showTime) {
if(longTime) {
@t.ToShortDateString() @t.ToLongTimeString();
} else {
@t.ToShortDateString() @t.ToShortTimeString();
}
} else {
@t.ToShortDateString()
}
}
</time>
}
ヘルパーは、次のような特定のビューで使用されます。
@model dynamic
<div>
<p> The current time is @DateTimeHelper(DateTime.Now)</p>
</div>