Rendering HTML from List property in Web Part

1.8k views Asked by At

I am trying to read some values from a SharePoint List and render them in my page as HTML. However, it literally shows the HTML tags on the Web Part page and fails to render it.

protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
  writer.WriteLine("<br />"); // this works
  writer.WriteLine(htbl["key"].ToString()); // html fails to render. literally renders the HTML in the string
}

I have seen following approaches already:

  1. Text to HTML – the JavaScript mentioned seems to be overkill in my opinion. Is there no easier way to accomplish this?

Please advise.

2

There are 2 answers

2
Tjassens On

Kris,

what do you put in the single line of text exactly?

I tried the following and this worked without any issues. If you compare this with your webpart class, do you see differences?

   using System;
    using System.ComponentModel;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using Microsoft.SharePoint;
    using Microsoft.SharePoint.WebControls;   

 namespace test.WebPart1
    {
        [ToolboxItemAttribute(false)]
        public class WebPart1 : WebPart
        {
            protected override void CreateChildControls()
            {

            }

            protected override void Render(HtmlTextWriter writer)
            {
                SPWeb web = SPContext.Current.Web;
                SPList list = web.Lists["testlist"];
                foreach (SPListItem item in list.Items)
                {
                    writer.Write(item["testcolumn"].ToString());
                }
            }
        }
    }
1
Kris Van den Bergh On

The reason was that the column was a multiple line of text and the type of text allowed was set to "Rich text (bold, italics, text alignment)", thus not making it possible to render the HTML properly. The resolution is to change it to plain text.