4

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?

1
  • 5
    I've noticed you have </html> before the <body>. Shouldn't it be at the very end of your markup (after </body>)? Commented Jul 23, 2012 at 1:01

2 Answers 2

4

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!

Sign up to request clarification or add additional context in comments.

Comments

1

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)  

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.