如何在asp.net核心中定义返回html的函数 [英] How to define function that returns html in asp.net core

查看:69
本文介绍了如何在asp.net核心中定义返回html的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我需要类似asp.net的东西

Basically I need something like old asp.net

@helper MakeNote(string content) {
    <p><strong>Note</strong>&nbsp;&nbsp; @content    </p>
}

或JSX

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

不能选择局部视图.我对返回IHtmlString的函数或向底层编写器写入的函数感到满意.

A partial view is not an option. I am happy with either a function returning an IHtmlString, or a function writing to the underlying writer.

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

It also needs to support Razor Syntax (not just string concatenation) inside the function.

推荐答案

ASP.NET Core 3.0 开始,我们可以声明包含标记的 Local Functions 作为模板方法. ,在剃刀代码块内:

Since ASP.NET Core 3.0, we can declare Local Functions containing markup to serve as templating methods, inside Razor Code Blocks:

@{
    void RenderName(string name)
    {
        <p>Name: <strong>@name</strong></p>
    }

    RenderName("Mahatma Gandhi");
    RenderName("Martin Luther King, Jr.");
}

哪个呈现以下HTML代码:

Which renders the following HTML Code:

<p>Name: <strong>Mahatma Gandhi</strong></p>
<p>Name: <strong>Martin Luther King, Jr.</strong></p>

文档:(仅出于完成目的)在 ASP.NET Core 2.0 中,我们可以使用模板化的Razor委托,该委托与<text></text> razor标记结合(显式分隔过渡) ),让我们做出类似于过去的ASP.NET MVC @helper标签的内容:

(just for sake of completion) In ASP.NET Core 2.0 we can use Templated Razor delegates, which combined with the <text></text> razor tag (Explicit Delimited Transition), allow us to make something similar to an old day's ASP.NET MVC @helper tag:

@{
    Func<string, object> RenderName = @<text>
        <p>
            Name: <strong>@item</strong>
        </p>;
    </text>;
}

<div>
    @RenderName("Victor")
</div>

哪个呈现以下HTML代码:

Which renders the following HTML Code:

<div>
    <p>
        Name: <strong>Victor</strong>
    </p>
</div>

文档:

Documentation: https://docs.microsoft.com/en-us/aspnet/core/mvc/views/razor?view=aspnetcore-2.0#templated-razor-delegates
Documentation <text></text>: https://docs.microsoft.com/en-us/aspnet/core/mvc/views/razor?view=aspnetcore-2.0#razor-code-blocks

这篇关于如何在asp.net核心中定义返回html的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆