Razor 如何在asp.net核心中定义返回html的函数
基本上我需要像旧的asp.net一样的东西Razor 如何在asp.net核心中定义返回html的函数,razor,asp.net-core,asp.net-core-mvc,Razor,Asp.net Core,Asp.net Core Mvc,基本上我需要像旧的asp.net一样的东西 @helper MakeNote(string content) { <p><strong>Note</strong> @content </p> } @helper MakeNote(字符串内容){ 注意@内容 } 或JSX MakeNote(note) { return (<div>Note {note}</div>
@helper MakeNote(string content) {
<p><strong>Note</strong> @content </p>
}
@helper MakeNote(字符串内容){
注意@内容
}
或JSX
MakeNote(note) {
return (<div>Note {note}</div>);
}
MakeNote(注释){
返回(注{Note});
}
局部视图不是一个选项。我很高兴函数返回IHtmlString,或者函数写入底层编写器
它还需要在函数内部支持Razor语法(不仅仅是字符串连接)。您可能正在寻找这种用法
下面是一个显示两种函数样式的示例。第一个使用传统的块体,第二个使用表达式体
它们在字符串上都有$@
前缀
在字符串中启用$
李>{interpoloation}
生成一个可以跨多行的逐字字符串@
@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>
@使用Microsoft.AspNetCore.Html
@功能
{
IHtmlContent MakeNote(字符串内容)
{
返回Html.Raw($@)
注意{content}
");
}
//一种使用速记方法的替代方法
IHtmlContent MakeNoteToo(字符串内容)=>Html.Raw($@)
注意{content}
");
}
@{
//另一种解析razor的方法
Func makenotetree=
@
注意{@item}
;
}
@MakeNote(“Foo”)
@MakeNoteToo(“酒吧”)
@MakeNoteThree(“Baz”)
编辑:添加了一个解析Razor的示例。有关详细信息,请参见。由于ASP.NET Core 3.0,我们可以在Razor代码块内声明本地函数,其中包含用作模板方法的标记: 它呈现以下HTML代码:
<p>Name: <strong>Mahatma Gandhi</strong></p>
<p>Name: <strong>Martin Luther King, Jr.</strong></p>
<div>
<p>
Name: <strong>Victor</strong>
</p>
</div>
姓名:Victor
文件:
文档
:您可以创建标记帮助器以返回自定义HTML标记。顺便说一句,你的或JSX部分使这个问题非常广泛(至少对我来说)这只是我从另一种语言需要的示例,我不知道它如何使问题广泛。我只给出了我需要的两个示例,标记帮助器还远远不够。它可以工作,但我想在该函数中使用Razor,不是字符串连接。@user2029276很好知道。我添加了一个在函数中使用Razor的示例。让我知道这对你是如何起作用的。我已经在github上看到了,但我认为这是一种黑客行为,而不是官方的解决方案。语法有点奇怪,参数没有命名。你能添加更多的参数吗?是的。您可以添加更多参数。不过,这样做的方法更像是一种技巧;它涉及将元组传递给func。要解决参数限制问题,可以使用元组。i、 e.Func CreateInput=@
如果函数返回void,则在html标记中调用大括号内的函数。像这样:{RenderName(“Victor”);}
@{
Func<string, object> RenderName = @<text>
<p>
Name: <strong>@item</strong>
</p>;
</text>;
}
<div>
@RenderName("Victor")
</div>
<div>
<p>
Name: <strong>Victor</strong>
</p>
</div>