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

编程入门 行业动态 更新时间:2024-10-28 14:31:56
本文介绍了如何在asp核心中定义返回html的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

Basically I need something like old asp

@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>

文档: docs.microsoft/zh-cn/aspnet/core/mvc/views/razor?view=aspnetcore-3.0#razor-code-blocks

(仅出于完成目的)在 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>

文档: docs.microsoft/zh-cn/aspnet/core/mvc/views/razor?view=aspnetcore-2.0#templated-razor-delegates 文档<text></text>: docs.microsoft/zh-cn/aspnet/core/mvc/views/razor?view=aspnetcore-2.0#razor-code-blocks

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

更多推荐

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

本文发布于:2023-11-16 17:24:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1606330.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   定义   核心   如何在   asp

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!