【问题标题】:CKEditor showing HTML tags in ASP.MVC with decodeCKEditor 在 ASP.MVC 中显示带有解码的 HTML 标签
【发布时间】:2018-07-04 14:20:08
【问题描述】:

一切都与创建/编辑页面完美配合,其中 CKEditor 对输入进行编码,服务器端返回已解码以供 CKEditor 显示。 当验证错误发生时,所有这些都超出了窗口,使页面在到达服务器后重新加载。

即使我在返回视图时进行解码,CKEditor 也不会正确呈现 html 标签。 如果我为同一个字段做 Html.Raw,我可以看到它正确显示 html,所以它没有解码问题。对于我的一生,我无法弄清楚为什么这种情况与编辑(将现有的 html 从 dB 加载到 CKEditor 中)有什么不同,而编辑工作完美。但是在页面重新加载时,一切都变得不正常了。

我尝试过的东西,解码,编码,都没有。为 CKEditor 初始化添加延迟。

服务器端返回码。

if (!ModelState.IsValid)
        {
            q..Text = System.Net.WebUtility.HtmlDecode(q.Text);
            return View(q);
        }

查看

    <div class="form-group">
        @Html.LabelFor(model => model.Text, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.TextAreaFor(model => model.Text, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Question.Text, "", new { @class = "text-danger" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(model => model.Text, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.Raw(Model.Text)
        </div>
    </div>

CKEditor 的 JavaScript

    var ckEditorInstance;

    $(document).ready(function () {
        CKEDITOR.replace('Text', { htmlEncodeOutput: true, enterMode: CKEDITOR.ENTER_BR });
        ckEditorInstance = CKEDITOR.instances.Text;
        ckEditorInstance.on('instanceReady', function () { UpdateTextArea(); });
        ckEditorInstance.on('change', function () { UpdateTextArea(); });

    });

    function UpdateTextArea() {
        ckEditorInstance.updateElement();
    };

</script>

使用 CKEditor v4.8.0 • 2017 年 13 月 12 日

显示问题的图像,在 CKEditor @Html.Raw(Model.Text) 输出下方,显示 html 已正确解码。

【问题讨论】:

    标签: javascript jquery html asp.net-mvc ckeditor


    【解决方案1】:

    通过使用 @Html.Raw(Model.Text) 而不是 TextAreaFor 解决了这个问题 与@Html.HiddenFor(model=&gt;Model.Text)

    在发布到服务器/控制器时保留数据 和 Javascript 更新隐藏字段和编码 html

       <script type="text/javascript">
    
        var ckEditorInstance;
    
        $(document).ready(function () {
            CKEDITOR.replace('ckEditorRaw', { enterMode: CKEDITOR.ENTER_BR });
            ckEditorInstance = CKEDITOR.instances.ckEditorRaw;
            ckEditorInstance.on('instanceReady', function () { UpdateTextArea(); });
            ckEditorInstance.on('change', function () { UpdateTextArea(); });
            });
    
        function UpdateTextArea() {
            ckEditorInstance.updateElement();
            //Set hidden field and escape html
            $("#Question_Text").val(new Option((ckEditorInstance.getData())).innerHTML)
        };
    
    </script>
    

    【讨论】:

      猜你喜欢
      • 2017-07-23
      • 2016-04-05
      • 2014-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多