How to use @Html.Raw() in @Html.TextAreaFor()

2020-05-09 09:37发布

问题:

I am using summernote to add Image, Video, text. Also, I save image or video as Html Code that is type string to database. When I retreive video or image from the database to display on summernote, it takes nearly 5 minutes and I don't know why. However, when I retrieve text from the database to display on summernote, there is no problem.

Here is model

public class Article
{
   [AllowHtml]
   [Column(TypeName = "varchar(MAX)")]
   public string Content { get; set; }
}

Here is View for summernote editor

@Html.TextAreaFor(x => Model.Content, new { @class = "", placeholder = @Blog.Helper.Resources.Content, @id = "summernote_1" })

In addition, If I use this below code in View

<div id="summernote_1">@Html.Raw(Model.Content)</div>

No problem with displaying video or image, but I cannot edit summernote. When I edit summernote, Model.Content is getting null.

If I use this below code in View

@Html.TextAreaFor(x => Model.Content, new { @class = "", placeholder = @Blog.Helper.Resources.Content, @id = "summernote_1" })

No problem with editing summernote, but displaying video or image takes nearly 5 minute.

Because of these reasons, I am trying to use this below code in View however this below code is getting error.

@Html.TextAreaFor(x => Html.Raw(Model.Content), new { @class = "", placeholder = @Blog.Helper.Resources.Content, @id = "summernote_1" })

Can I use html.raw in html.TextAreaFor or What can I do for this issue to display video or image and edit summernote. Sorry my bad english and I hope that someone can help me.

回答1:

Html.Raw method returns System.Web.IHtmlString, I think what you need is just passing string property containing HTML tags (AFAIK Html.Raw helper can't be used inside other HTML helpers like DisplayFor or TextBoxFor).

It is possible to use HttpUtility.HtmlDecode for Content property before TextAreaFor as shown by this example (especially if HTML tags are unknowingly encoded):

@model Article

@{
    Model.Content = HttpUtility.HtmlDecode(Model.Content);
}

@Html.TextAreaFor(x => x.Content, new { @class = "", placeholder = @Blog.Helper.Resources.Content, @id = "summernote_1" })

By using this way, you can render HTML tags properly from viewmodel's string property without losing model binding.



回答2:

.textarea {
padding: 2px;
width: 250px;
height: 200px;
border: solid 1px #e0e0eb;
overflow: scroll;
overflow-y: scroll;
overflow-x: hidden;
}

write your html content using @Html.Raw() inside a div that contains a class "textarea".

<div class="textarea"> @Html.Raw(Model.NOTE) </div>