用动态HTML包裹Razor页面

时间:2019-01-17 21:04:13

标签: javascript c# razor asp.net-core razor-pages

基本上,我想在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();
    }

example.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实现此目标?

1 个答案:

答案 0 :(得分:1)

页面加载后,您可以使用Jquery将文本移动到content div上:

后面的代码:

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>

}