如何在@Html.TextAreaFor() 中使用@Html.Raw()

0 asp.net-mvc summernote

我正在使用 summernote 添加图像、视频、文本。此外,我将图像或视频保存为 Html 代码,该代码类型为字符串到数据库。当我从数据库中检索视频或图像以显示在 summernote 上时,需要将近 5 分钟,我不知道为什么。但是,当我从数据库中检索文本以显示在 summernote 上时,没有问题。

这是模型

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

这是 Summernote 编辑器的视图

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

另外,如果我在视图中使用下面的代码

<div id="summernote_1">@Html.Raw(Model.Content)</div>
Run Code Online (Sandbox Code Playgroud)

显示视频或图像没问题,但我无法编辑summernote。当我编辑summernote 时,Model.Content 变空了。

如果我在视图中使用下面的代码

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

编辑summernote没问题,但显示视频或图像需要近5分钟。

由于这些原因,我尝试在 View 中使用下面的代码,但是下面的代码出现错误。

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

我可以在 html.TextAreaFor 中使用 html.raw 还是我可以为这个问题做些什么来显示视频或图像并编辑summernote。对不起,我的英语不好,我希望有人能帮助我。

Tet*_*oto 6

Html.Raw方法返回System.Web.IHtmlString,我认为您需要的只是传递string包含 HTML 标签的属性(AFAIKHtml.Raw助手不能在其他 HTML 助手中使用,例如DisplayForTextBoxFor)。

如本示例所示,可以使用HttpUtility.HtmlDecodeforContent之前的属性TextAreaFor(尤其是在不知情的情况下对 HTML 标签进行了编码):

@model Article

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

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

通过使用这种方式,您可以从 viewmodel 的 string 属性正确呈现 HTML 标签,而不会丢失模型绑定。