首页 > 解决方案 > 使用动态 HTML 包装 Razor 页面

问题描述

基本上我想在 Razor 页面的输出周围包装一些动态生成的 HTML。出于本示例的目的,我们假设string wrapper正在从数据库接收动态 HTML 字符串。但是它总是包括<div id="content"></div>

从example.cshtml.cs考虑这个OnGetAsync方法

public async Task<IActionResult> OnGetAsync()
{
        //wrapper will be dynamically assigned from database
        //but will also ALWAYS contain div id=content

        string wrapper = @"<html><head></head><body><h1>HELLO</h1>" &_
                "<div id="content"></div></body></html>"

        return Page();
    }

示例.cshtml:

@page
@model ExampleModel

@section CSS {

    <style type="text/css">
        .midnight {
            color: #ccc;
        }
    </style>

}

<p>this is a test</p>

执行后return Page();,我想以某种方式获取生成的 HTML 并将其注入到内容 div 中的包装器代码中。

理想情况下,结果输出是这样的:

<html>
   <head>
   </head>
   <body>
   <h1>HELLO</h1>
   <div id="content"> 
      <!-- injected from OnGetAsync() -->         
      <!-- omitted for brevity
           more code including @section CSS -->
      <p>this is a test</p>
      <!-- END injected from OnGetAsync() -->  
   </div>
   </body>
</html>

您将如何使用 Razor Pages、asp.net core 2.2 和/或 javascript 完成此任务?

标签: javascriptc#razorasp.net-corerazor-pages

解决方案


您可以在页面加载后使用 Jquery 将文本移动到contentdiv :

后面的代码:

public string Content { get; set; } 

public async Task<IActionResult> OnGetAsync()
{
    //wrapper will be dynamically assigned from database
    //but will also ALWAYS contain div id=content

    string wrapper = @"<html><head></head><body><h1>HELLO</h1><div id='content'></div></body></html>";
    Content = wrapper;

    return Page();
}

剃刀页面:

<p id="orginalConent">this is a test</p>

@Html.Raw(@Model.Content)

@section Scripts {
    <script>
        $(function () {
            var orginalConent = $("#orginalConent");
            $('#content').append($('<p>').text(orginalConent.text()));
            orginalConent.remove();           
        })

    </script>

}

推荐阅读