【问题标题】:Wrap Razor Page with Dynamic HTML使用动态 HTML 包装 Razor 页面
【发布时间】:2019-06-12 03:29:35
【问题描述】:

基本上,我想在 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 完成此任务?

【问题讨论】:

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


    【解决方案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>
    
    }
    

    【讨论】:

      猜你喜欢
      • 2012-06-26
      • 2021-09-25
      • 1970-01-01
      • 2016-06-09
      • 2020-10-02
      • 2023-01-18
      • 2019-02-06
      • 1970-01-01
      • 2015-02-20
      相关资源
      最近更新 更多