Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 598
MrDuk Avatar asked Oct 18 '25 18:10

MrDuk


1 Answers

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!

like image 122
Brian Genisio Avatar answered Oct 20 '25 09:10

Brian Genisio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!