javascript - 使用动态 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 完成此任务?
解决方案
您可以在页面加载后使用 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>
}
推荐阅读
- javascript - 如何使用键盘上的 w 和 s 键使第二个 div 上下移动?
- interpreter - 是否有任何解释语言使用 int、float 和 string 等关键字来声明变量?
- python - 如何将 JupyterLab 扩展与 Python 内核交互?
- macos - PyCharm:使用 SIFT 和 opencv-contrib (Mac)
- python - 如何获取numpy中唯一值计数的返回值?
- c# - 使用 streamreader 在文本文件中查找特定用户条目并在标签中显示第 5 个组件
- python - How to execute python file from other directory?
- excel - 将文件保存在超链接后面
- github - 如何在 Red Hat OpenShift 中配置 GitHub Webhook URL?
- docker - 将当前本地 ip 传递给 docker-compose 中的 dnsmasq 命令