Nathiel Barros
Nathiel Barros

Reputation: 715

How to construct properly a html string in C#

I need to create this html string :

<table cellspacing="2" style="width:100%">
    <tr height="30" nowrap="NOWRAP" width="200" bgcolor="#f4f4f4">
      <th>Product</th>
      <th>Category</th> 
      <th>Price</th>
   </tr>
   <tr>
      <td>Replace</td>
      <td>Replace</td>
      <td>Replace</td>
  </tr>
</table>

And I have a List of items that I intend to replace. I Was trying to do with StringBuilder but it wasn't working!

Upvotes: 0

Views: 226

Answers (1)

Igor
Igor

Reputation: 62308

You can use the @ for verbatim string and double the " marks to escape them. Also you can use string.Format with {} placeholders to inject values although they are not html encoded so if you have characters like < in the string they would need to be escaped. This is 1 variant of many and without you sharing what you have so far it is as good as any answer you might get.

var html = string.Format(
@"<table cellspacing=""2"" style=""width:100%"">
    <tr height=""30"" nowrap=""NOWRAP"" width=""200"" bgcolor=""#f4f4f4"">
      <th>Product</th>
      <th>Category</th> 
      <th>Price</th>
   </tr>
   <tr>
      <td>{0}</td>
      <td>{1}</td>
      <td>{2}</td>
  </tr>
</table>", listItem[0], listItem[1], listItem[2]);

Upvotes: 2

Related Questions