1

My Goal

Save and post html to a blog post using C# ASP.Net MVC, using best practices

How do I do this?


Below is the source that causes the following error:

Error 2 Operator '.' cannot be applied to operand of type 'lambda expression'


ArticleContent.CS (controller)

  // 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 (Model)

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

index.cshtml (View) <-- Trigger

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

index.cshtml (Full Version of View)

<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>

Questions as Resources

How to save html to database and retrieve is properly

Text both raw and parsed html


Future Note

Using .Substring(0,250) with a null value creates an error due to strings 0 - 250 not existing.

Community
  • 1
  • 1
Joseph Casey
  • 1,283
  • 1
  • 14
  • 34
  • 1
    What code triggers the error? I'm guessing it's the HtmlDecode stuff, but it's good if your post is specific. – DWright May 13 '15 at 22:12
  • The index.cshtml (view snipper) which reads: @Html.Raw(HttpUtility.HtmlDecode((modelItem => modelItem.PageBody).ToString().Substring(0,250))) – Joseph Casey May 13 '15 at 22:13
  • shouldn't it just be `modelItem.PageBody.ToString()` not `(modelItem => modelItem.PageBody).ToString()`? – jamesSampica May 13 '15 at 22:39

1 Answers1

2

The HttpUtility.HtmlDecode takes a string and returns another. But you pass a lambda expression (modelItem => modelItem.PageBody) on that was the ToString- and SubString methods are called.

You must change your code to the following:

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

In that code, you give the PageBody property to the HtmlDecode method and then call SubString. This string is given to the Raw method.

Much methods like @Html.EditorFor take a lambda as an argument, but HtmlDecode needs a string. That is the main problem.

PS: If PageBodyis not a string, you must call ToStringon it before passing it to HtmlDecode.

Koopakiller
  • 2,838
  • 3
  • 32
  • 47
  • This doesn't work inside a foreach loop? Both item.PageBody and Model.PageBody are pulling up a NullReferenceException error. @ foreach (var item in Model{ – Joseph Casey May 14 '15 at 17:34
  • Never mind. I found out the.substring(0,250) creates an error if the value for the PageBody string is null. Any suggestions? – Joseph Casey May 14 '15 at 21:31
  • @JosephCasey I suggest you check it with the `?:` Operator: `@(Model.PageBody == null ? string.Empty : Html.Raw(HttpUtility.HtmlDecode(Model.PageBody).Substring(0,250)))` – Koopakiller May 14 '15 at 21:37
  • Html.Raw outputs IHtmlString so "? string.Empty" won't work. I'm checking for a way to check if IHTMLStrings are null. – Joseph Casey May 14 '15 at 21:47
  • 1
    Ok, I am not so familiar with MVC/Razor...but you can also change the Position of the `?:`: `@Html.Raw(string.IsNullOrEmpty(Model.PageBody) ? string.Empty : HttpUtility.HtmlDecode(Model.PageBody).Substring(0,250))` – Koopakiller May 14 '15 at 21:54
  • That's the ticket. I also should note that I wrote it to pull the inner text instead since `

    blah blah blah` would be really bad.

    – Joseph Casey May 14 '15 at 21:58