在 Razor 中将动态 HTML 内容渲染为变量 [英] Rendering dynamic HTML content into variable in Razor

查看:39
本文介绍了在 Razor 中将动态 HTML 内容渲染为变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将动态 HTML 内容呈现为一个变量,以便稍后将其传递给一个函数.原因是,我通过另一个平台接收实际内容,我可以使用内部函数将其打印出来.此函数接受要放入占位符的值.

I want to render dynamic HTML content into a variable to later pass it to a function. The reason is, that I receive the actual content through another platform and I can print it out using an internal function. This function accepts values to put into placeholders.

示例:

This is my content:
{mytable}
Blah

现在我可以在 mytable 上设置任何内容.好的.目前我想放的内容如下.

Now I can set any content on mytable. Good. The content I want to put there is currently the following.

@using System.Data
@model Dictionary<string, DataView>
<table>
    @foreach (var group in Model)
    {
        <tr>
            <th colspan="3">@group.Key</th>
        </tr>

        foreach (DataRowView data in group.Value)
        {
            <tr>
                <td>@data.Row["col1"]</td>
                <td>@data.Row["col2"]</td>
                <td>@data.Row["col3"]</td>
            </tr>
        }
    }
</table>

嗯.将上述输出实际呈现为变量的最佳方法是什么?我首先想到的只是将每一行 HTML 附加到一个字符串中,但对我来说这听起来效率很低且很弱.

Well. What is the best way to actually render the above output into a variable? I firstly thought of just appending every HTML line into a string, but it sounds rather inefficient and weak to me.

我不是 ASP.NET 的专家,我来自 PHP,我对输出缓冲区有一些了解.这是一种可能的方式吗?你会推荐什么?

I'm not an expert in ASP.NET, I come from PHP and I know a bit about output buffers. Is this a possible way? What would you recommend?

推荐答案

您可以创建一个ViewHelper:

@helper RenderTable(Dictionary<string, System.Data.DataView> model)
{
    <table>
        @foreach (var group in Model)
        {
            <tr>
                <th colspan="3">@group.Key</th>
            </tr>

            foreach (System.Data.DataRowView data in group.Value)
            {
                <tr>
                    <td>@data.Row["col1"]</td>
                    <td>@data.Row["col2"]</td>
                    <td>@data.Row["col3"]</td>
                </tr>
            }
        }
    </table>
}

然后调用它:

@{
    string output = RenderTable(someData).ToHtmlString();
}

这篇关于在 Razor 中将动态 HTML 内容渲染为变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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