You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从.NET ViewData取HTML字符串,jQuery追加到div显示纯文本的解决方法

问题:HTML字符串追加到Div后显示为纯文本

场景与代码示例

从.NET的ViewData获取HTML字符串,在jQuery中读取后追加到指定Div,但最终显示为纯文本而非渲染后的表格。

读取ViewData的JS代码

var htmlTranTable = '@ViewData["tblView"]';    
$('#divTransactions').append(htmlTranTable);

接收的HTML字符串(已转义)

var htmlTranTable = `<table class='table table-bordered row-border table-responsive' id='htmlTableTransactions'>
   <thead>
      <tr>
         <th class='text-nowrap'>Transaction No</th >
         <th class='text-nowrap'>Status</th >
      </tr>
   </thead>
   <tbody>
      <tr>
         <td>510002500007484</td>
         <td>Completed With Migration Successful</td>
      </tr>
      <tr>
         <td>510002500007475</td>
         <td>Completed With Migration Successful</td>
      </tr>     
   </tbody>
</table>`

目标HTML容器

<div class="table-responsive" id="divTransactions" style="overflow:hidden"></div>

尝试的追加代码

$('#divTransactions').append(htmlTranTable); 
// 或
document.getElementById("divTransactions").innerHTML += htmlTranTable;

原因分析

ViewData返回的是HTML转义后的字符串(包含&lt;、&gt;这类HTML实体字符),浏览器会将其视为普通文本内容,不会解析为HTML标签进行渲染。

解决方法

方法1:.NET端输出未转义的HTML

使用Html.Raw直接输出原生HTML字符串,让JS拿到可直接解析的代码:

var htmlTranTable = '@Html.Raw(ViewData["tblView"])';    
$('#divTransactions').append(htmlTranTable);

方法2:JS端解码HTML实体

若无法修改.NET端代码,可在JS中先解码转义字符再追加:

// 解码HTML实体的工具函数
function decodeHtml(html) {
    const tempElement = document.createElement("textarea");
    tempElement.innerHTML = html;
    return tempElement.value;
}

var htmlTranTable = '@ViewData["tblView"]';    
var decodedHtml = decodeHtml(htmlTranTable);
$('#divTransactions').append(decodedHtml);

方法3:使用jQuery的.html()处理追加

如果需要保留原有内容并追加新HTML,可通过.html()拼接处理:

var htmlTranTable = '@Html.Raw(ViewData["tblView"])';    
$('#divTransactions').html($('#divTransactions').html() + htmlTranTable);

内容的提问来源于stack exchange,提问作者user19453028

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 04:57:23