理解ASP.NET MVC引擎处理模型字符串的默认行为,涉及Html.Raw()和HttpUtility.HtmlDecode()

MVC引擎默认会将Model属性值中包含的html字符串做encode,所以如属性中包含类似 <br> 这样的标记,MVC引擎会将它们转换成html实体码 %3Cbr%3E 

所以1:在编辑时

<div class="col-md-10">
    @Html.TextArea("Eval", HttpUtility.HtmlDecode(main.Eval), new { @class = "form-control textAreaStyle", name = "" })
</div>

所以2:在显示时,如果需要将当需要将 <br> 作为"原生HTML字符串"被浏览器解析,即代表它本身html编码含义.如 <br解析为换行,需要使用 @Html.Raw() 方法

<label class="col-md-9 control-label font-normal">@Html.Raw(@Model.Main.Eval)</label>

所以3:在提交时,JS解决方法

HtmlUtil.htmlEncode("Xxx");
//定义部分
var HtmlUtil = {
    htmlEncode: function (html) {
        var temp = document.createElement("div");
        (temp.textContent != undefined) ? (temp.textContent = html) : (temp.innerText = html);
        var output = temp.innerHTML;
        temp = null;
        return output;
    },
    htmlDecode: function (text) {
        var temp = document.createElement("div");
        temp.innerHTML = text;
        var output = temp.innerText || temp.textContent;
        temp = null;
        return output;
    }
};
原文地址:https://www.cnblogs.com/zhuji/p/10038666.html