如果把带有html的标记的字符串从服务端传到页面上,需要对其进行编码。Ajax.JavaScriptStringEncode()

时间:2021-07-26 10:08:39

controller:

            StringBuilder s = new StringBuilder();
string a = "<script>alert('我StringBuilder')</script>文档内容";
s.AppendFormat("<h1>{0}</h1><h1>测试</h1>", a);
string t=s.ToString();
ViewBag.newMes = t;

cshtml:

    <div id="haha"></div>
<script type="text/javascript">
$(document).ready(function () {
var newMes = '@Ajax.JavaScriptStringEncode(ViewBag.newMes)';
document.getElementById("haha").innerHTML =newMes;
});
</script>