基本上我需要像旧的asp.net
@helper MakeNote(string content) {
<p><strong>Note</strong> @content </p>
}
或JSX
MakeNote(note) {
return (<div>Note {note}</div>);
}
部分视图不是一种选择。我很满意返回IHtmlString的函数,或写入底层编写器的函数。
它还需要在函数内部支持Razor语法(不仅仅是字符串连接)。
您可能正在寻找使用@functions
的Html.Raw
。
这是一个显示两种函数样式的示例。第一个使用传统的块体,第二个使用表达体。
它们都在字符串上有$@
前缀。
$
使字符串中的{interpoloation}
成为可能。@
创建一个逐字符串,可以跨越多行。第三种方式是一种让我们在函数内部解析Razor的黑客攻击。它就像我们似乎能够获得原始的@helper
语法一样接近。
SomeRazorFile.cshtml
@using Microsoft.AspNetCore.Html
@functions
{
IHtmlContent MakeNote(string content)
{
return Html.Raw($@"
<p>
<strong>Note</strong> {content}
</p>
");
}
// an alternative that uses method shorthand
IHtmlContent MakeNoteToo(string content) => Html.Raw($@"
<p>
<strong>Note</strong> {content}
</p>
");
}
@{
// an alternative that parses razor
Func<string, IHtmlContent> MakeNoteThree =
@<p>
<strong>Note</strong> {@item}
</p>;
}
<div>
@MakeNote("Foo")
@MakeNoteToo("Bar")
@MakeNoteThree("Baz")
</div>
编辑:添加了一个解析Razor的示例。有关详细信息,请参阅https://github.com/aspnet/Razor/issues/715。