Is there a way for Code Block feature to keep line breaks in CKEditor5 with ASP.Net Core?

Viewed 99

I am making a bulletin board system using CKEditor. Most of the features work just fine, but when editing an existing post, the all line breaks in the text are removed from the code block.

Image of create a post

Image of edit a post

Image of part of the response source

I googled as much as possible to solve this problem, but the methods I found were to no avail, so I removed it from the code again. It seems that line breaks are removed while processing the source internally in CKEditor5, is there any way?

  • Replace all line breaks with <br /> tags.
  • Add /\r|\n/g to protectedSource

The following is the view file for that feature.

@model BBSArticleWriteView

@{
    // Action name of the current view 
    var thisActionString = @ViewContext.RouteData.Values["action"].ToString();

    if (Model.ArticleId == null)
        ViewData["Title"] = "Writing";
    else
        ViewData["Title"] = "Editing";
}

<p class="page-header">@ViewData["Title"]</p>

<form asp-action="@thisActionString" id="editor-form">
    <input asp-for="ArticleId" value="@Model.ArticleId" hidden />
    <div>
        <input asp-for="Title" required placeholder="Please enter a title." class="form-control w-100 mb-2" />
    </div>
    <div>
        <textarea name="Contents" id="editor">
            @Html.Raw(Model.Contents)
        </textarea>
    </div>
    <div>
        <input class="btn btn-sm btn-primary" type="submit" value="Save" onsubmit="Editor.submit()" />
        <button class="btn btn-sm btn-primary" type="button" href="##" onclick="history.back()">Back</button>
    </div>
</form>
<style>
    .ck-editor__editable_inline {
        min-height: 400px;
    }
</style>

@section Scripts {
<script src="~/lib/ckeditor5/ckeditor.js" asp-append-version="true"></script>
<script>
    class Editor{
        static submit() {
            return true;
        }
    }

    ClassicEditor
        .create(document.querySelector('#editor'),
        {
            simpleUpload:{
                uploadUrl: "@Url.Action(nameof(CreatorFront.Controllers.FileController.Upload), "File")",
                withCredentials: true
            },
            protectedSource:[
                /\r|\n/g
            ]
        })
        .catch(error => {
            console.error(error);
        });
</script>
}

And here is the controller action that puts data into the view model.

[HttpGet]
public async Task<IActionResult> BBSEdit(int id)
{
    var user = await _userManager.GetUserAsync(HttpContext.User);
    if(user == null)
    {
        return RedirectToAction("Index", "Home");
    }

    var article = _cContext.BBSArticle.First(a => a.ArticleId == id);
    if(article == null)
    {
        return RedirectToAction(nameof(BBSList));
    }

    if(user.Id != article.UserId)
    {
        return RedirectToAction(nameof(BBSList));
    }

    var model = new BBSArticleWriteView();
    CopyProperties(model, article);

    return View(nameof(BBSWrite), model);
}

The following is a function that puts content data in DB.

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> BBSWrite(BBSArticleWriteView article)
{
    if(ModelState.IsValid)
    {
        var user = await _userManager.GetUserAsync(HttpContext.User);
        if(user == null)
        {
            RedirectToAction("Index", "Home");
        }

        // XSS attacks prevent
        article.Contents = _htmlSanitizer.Sanitize(article.Contents);

        var currentDateTime = DateTime.Now;

        CreatorLib.Models.BBS.BBSArticle data = new CreatorLib.Models.BBS.BBSArticle()
        {
            ArticleId = _cContext.BBSArticle.Max(a => a.ArticleId) + 1,
            MainCategory = article.MainCategory,
            SubCategory = article.SubCategory,
            UserId = user.Id,
            Title = article.Title,
            Contents = article.Contents,
            Status = CreatorLib.Models.BBS.ArticleStatus.A,
            IpAddress = HttpContext.Connection.RemoteIpAddress.ToString(),
            RegisteredTime = currentDateTime,
            LastUpdatedTime = currentDateTime,
            HasMedia = article.HasMedia
        };
        _cContext.BBSArticle.Add(data);
        await _cContext.SaveChangesAsync();
        return RedirectToAction(nameof(BBSList));
    }
    return View(article);
}

Here, it is confirmed that HtmlSanitizer has absolutely no impact on this issue. In DB, line breaks are fully preserved.

0 Answers
Related