【问题标题】:How do you sanitize and publish HTML into ASP.Net View?您如何清理 HTML 并将其发布到 ASP.Net 视图中?
【发布时间】:2023-04-03 10:53:01
【问题描述】:

我的目标

使用 C# ASP.Net MVC 保存 html 并将其发布到博客文章中,使用最佳实践

我该怎么做?


以下是导致以下错误的来源:

错误 2 运算符 '.'不能应用于“lambda”类型的操作数 表达'


ArticleContent.CS(控制器)

  // POST: Article/Articles/Create
    [HttpPost]
    [ValidateAntiForgeryToken]
    [Authorize(Roles = "canEdit")]
    public ActionResult Create([Bind(Include = "PostId,Title,PublishDate,CreateDate,ModifyDate,Author,PageBody,Feature,Published,Excerpt,CreateDateUTC,PublishDateUTC,ModifyDateUTC,CanonicalUrl,UrlSlug,Category,Tag")] ArticleContent articles)
    {
        if (ModelState.IsValid)
        {
            db.Articles.Add(articles);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(articles);
    }

Article.cs(模型)

    [Display(Name = "Body of Article")]
    public string PageBody { get; set; }

index.cshtml(视图)
@Html.Raw(HttpUtility.HtmlDecode((modelItem => modelItem.PageBody).ToString().Substring(0,250)))

index.cshtml(完整版视图)

<section class="bg-ocean row light text-center shelve">
        @if (User.IsInRole("canCreate"))
        {
            <button class="btn btn-info btn-lg btn-block">
                @Html.ActionLink("Create New", "Create")
            </button>
        }
        @foreach (var item in Model)
        {
                <article class="headline">
                        <div class="col-xs-12 col-md-7 headline-image np nm">
                            <a href="@Url.Action("Details", "Details", new { id = item.PostId })" target="_blank">
                                <img src="@Html.DisplayFor(modelItem => item.Feature)" />
                                <span>
                                    @Html.DisplayFor(modelItem => item.Categories)
                                </span>
                            </a>
                        </div>
                        <div class="col-xs-12 col-md-5 bg-light headline-content np nm">
                            <a href="@Url.Action("Details", "Details", new { id = item.PostId })" target="_blank">
                                <small class="dark">@Html.DisplayFor(modelItem => item.ModifyDate)</small>
                                <h2 class="media-heading dark">@Html.DisplayFor(modelItem => item.Title)</h2>
                                <hr />
                                <p>@Html.DisplayFor(modelItem => item.Excerpt)</p>
                            </a>
                            <div class="headline-footer">
                                <div class="btn-group btn-group-justified">
                                    <span class="btn btn-default" role="button"><i class="fa fa-eye"></i> 172</span>
                                    <span class="btn btn-default" role="button"><i class="fa fa-comment"></i><a href="@Url.Action("Details", "Details", new { id = item.PostId + "%23disqus_thread" })"></a></span>
                                    <span class="btn btn-default highlight" role="button"><i class="fa fa-share"></i> 210</span>
                                </div>
                            </div>
                        </div>
                            @if (User.IsInRole("canEdit"))
                            {
                                @Html.ActionLink("E", "Edit", new { id = item.PostId })
                            }
                            @if (User.IsInRole("canDelete"))
                            {
                                @Html.ActionLink("D", "Delete", new { id = item.PostId })
                            }
            </article>
        }
</section>

问题作为资源

How to save html to database and retrieve is properly

Text both raw and parsed html


未来说明

.Substring(0,250) 与 null 值一起使用会产生错误,因为字符串 0 - 250 不存在。

【问题讨论】:

  • 什么代码触发了错误?我猜这是 HtmlDecode 的东西,但如果你的帖子是具体的,那就太好了。
  • index.cshtml(查看截图),内容为:@Html.Raw(HttpUtility.HtmlDecode((modelItem => modelItem.PageBody).ToString().Substring(0,250)))
  • 不应该只是modelItem.PageBody.ToString()而不是(modelItem =&gt; modelItem.PageBody).ToString()吗?

标签: c# asp.net asp.net-mvc razor


【解决方案1】:

HttpUtility.HtmlDecode 接受一个字符串并返回另一个。但是您传递了一个 lambda 表达式 (modelItem =&gt; modelItem.PageBody),即调用了 ToString- 和 SubString 方法。

您必须将代码更改为以下内容:

@Html.Raw(HttpUtility.HtmlDecode(Model.PageBody).Substring(0,250))

在该代码中,您将PageBody 属性赋予HtmlDecode 方法,然后调用SubString。该字符串被赋予Raw 方法。

@Html.EditorFor 这样的许多方法都将 lambda 作为参数,但 HtmlDecode 需要一个字符串。这是主要问题。

PS:如果PageBody不是字符串,则必须先调用ToString,然后再将其传递给HtmlDecode

【讨论】:

  • 这在 foreach 循环中不起作用? item.PageBody 和 Model.PageBody 都出现 NullReferenceException 错误。 @foreach(模型中的变量项{
  • 没关系。我发现如果 PageBody 字符串的值为 null,则 .substring(0,250) 会产生错误。有什么建议吗?
  • @JosephCasey 我建议您使用?: 操作员:@(Model.PageBody == null ? string.Empty : Html.Raw(HttpUtility.HtmlDecode(Model.PageBody).Substring(0,250)))
  • Html.Raw 输出 IHtmlString 所以 "?string.Empty" 不起作用。我正在检查一种方法来检查 IHTMLStrings 是否为空。
  • 好吧,我对 MVC/Razor 不是很熟悉...不过你也可以更改 ?: 的位置:@Html.Raw(string.IsNullOrEmpty(Model.PageBody) ? string.Empty : HttpUtility.HtmlDecode(Model.PageBody).Substring(0,250))
猜你喜欢
  • 1970-01-01
  • 2023-01-22
  • 2018-11-24
  • 1970-01-01
  • 2021-02-09
  • 2015-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多