Search code examples
c#asp.nethtmlstringemail-templates

How to assign HTML value to a asp.net string variable


I am using asp.net and C#. I want to send mail to my user in HTML format, I have the content in HTML format let say like this

    <table style="width:100%;">
     <tr>
       <td style="width:20%; background-color:Blue;"></td>
       <td style="width:80%; background-color:Green;"></td>
     </tr>
    </table>

Now I am unable to assign this to a string variable, so that I could send it as a mail. Please let me know how can I bind this whole HTML content into a varibale.

Also, please note that the above code is only a demo, I have around 100 lines of HTML code.


Solution

  • If you want to explicitly declare the string in code:

    string html =
    @"<table style=""width:100%;""> 
         <tr> 
           <td style=""width:20%; background-color:Blue;""></td> 
           <td style=""width:80%; background-color:Green;""></td> 
         </tr> 
        </table>";
    

    In response to your comment, to insert values, it's simple enough to use StringBuilder to build a string in memory, eg.,

    var html = new StringBuilder("<table style=\"width:100%;\">");
    html.Append("<tr>");
    html.Append("<td style=\"width:20%; background-color:Blue;\">");
    html.Append(yourAuthorNameString);
    //etc...
    

    or move to a proper html builder or template system like the HTML Agility Pack or NVelocity