加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

razor – 如何定义在asp.net核心中返回html的函数

发布时间:2020-12-15 19:53:13 所属栏目:asp.Net 来源:网络整理
导读:基本上我需要像旧的asp.net @helper MakeNote(string content) { pstrongNote/strongnbsp;nbsp; @content /p} 或JSX MakeNote(note) { return (divNote {note}/div);} 部分视图不是一种选择.我很满意返回IHtmlString的函数,或写入底层编写器的函数. 它还需要
基本上我需要像旧的asp.net
@helper MakeNote(string content) {
    <p><strong>Note</strong>&nbsp;&nbsp; @content    </p>
}

或JSX

MakeNote(note) {
   return (<div>Note {note}</div>);
}

部分视图不是一种选择.我很满意返回IHtmlString的函数,或写入底层编写器的函数.

它还需要在函数内部支持Razor语法(不仅仅是字符串连接).

解决方法

您可能正在寻找使用 Html.Raw@functions.

这是一个显示两种函数样式的示例.第一个使用传统的块体,第二个使用表达体.

它们都在字符串上有$@前缀.

> $在字符串中启用{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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读