MrDuk
MrDuk

Reputation: 18312

How to display content of StringBuilder as HTML?

I build a string that is supposed to be used to generate an HTML table. I can't get the text to display as HTML though, it just writes as plain text.

Here's where I build the string: StringBuilder HTMLTable = new StringBuilder();

    HTMLTable.AppendLine("<html>");
    HTMLTable.AppendLine("<head>");
    HTMLTable.AppendLine("<style type=\"text/css\">");
    HTMLTable.AppendLine("    .thd {background: rgb(220,220,220); font: bold 10pt Arial; text-align: center;}");
    HTMLTable.AppendLine("    .team {color: white; background: rgb(100,100,100); font: bold 10pt Arial; border-right: solid 2px black;}");
    HTMLTable.AppendLine("    .winner {color: white; background: rgb(60,60,60); font: bold 10pt Arial;}");
    HTMLTable.AppendLine("    .vs {font: bold 7pt Arial; border-right: solid 2px black;}");
    HTMLTable.AppendLine("    td, th {padding: 3px 15px; border-right: dotted 2px rgb(200,200,200); text-align: right;}");
    HTMLTable.AppendLine("    h1 {font: bold 14pt Arial; margin-top: 24pt;}");
    HTMLTable.AppendLine("</style>");
    HTMLTable.AppendLine("</head>");
    HTMLTable.AppendLine("</html>");

    HTMLTable.AppendLine("<body>");
    HTMLTable.AppendLine("<h1>Tournament Results</h1>");
    HTMLTable.AppendLine("<table border=\"0\" cellspacing=\"0\">");
    for (int row = 0; row <= max_rows; row++)
    {
        cumulative_matches = 0;
        HTMLTable.AppendLine("    <tr>");

// etc. etc.

And then I add this string to the viewbag associated with my .cshtml file. I've tried things like:

 <text>@ViewBag.bracketHTML</text>

but that doesn't work. Any ideas?

Upvotes: 4

Views: 22674

Answers (2)

Anand
Anand

Reputation: 14935

There are a quite few ways to do it. You could it by either

@(new HtmlString(ViewBag.bracketHTML)) 

Or you could use

@MvcHtmlString.Create(ViewBag.bracketHTML)

Or you could use @Html.Raw

@Html.Raw(ViewBag.bracketHTML)  

Upvotes: 1

Brian Genisio
Brian Genisio

Reputation: 48147

First, you should take @Zhihao's suggestion and fix the HTML end tag.

After that, this should work for you:

First, set the value of the HTML using the builder's ToString() function to a property of the ViewBag in the controller:

var builder = new StringBuilder();
builder.AppendLine("<div>");
builder.AppendLine("Testing 123");
builder.AppendLine("</div>");

ViewBag.testing = builder.ToString();

Next, print it out using Html.Raw():

@Html.Raw(ViewBag.testing)

Seems to work well!

Upvotes: 4

Related Questions