简体   繁体   中英

how to place C# code/syntax within concatenated string

I have a string that I am concatenating so as to then generate a pdf using C# and ITextSharp. I have some values such as paymentId from my model that I would like to also display on the pdf.

The pdf is generated successfully until I try to add the values from my model eg "onlineTransactionViewModel.OnlineTransaction.PaymentId"

   var example_html = @"<html>
    <body style = 'font-family: Helvetica Neue, Helvetica, Helvetica, Arial, sans-serif; text-align: center; color: #777'>;
    <div class='invoice- box'>
    <table>
     <tr class='top'>
    <td colspan=""5"">
        <table> 
           <tr> 
                <td colspan= ""3"">'onlineTransactionViewModel.OnlineTransaction.PaymentId' ""</br>"" ""onlineTransactionViewModel.OnlineTransaction.PayFastReference"" ""</br>""  ""onlineTransactionViewModel.OnlineTransaction.PayFastReference""
               <td class= ""title"" style = 'text - align:right'></ td >
               </ tr >
               </ table >
               </ table >
               </ div >
               </ body >
               </ html>"; 
            

   
             using (var htmlWorker = new iTextSharp.text.html.simpleparser.HTMLWorker(doc))
             {

                 //HTMLWorker doesn't read a string directly but instead needs a TextReader (which StringReader subclasses)
                 using (var sr = new StringReader(example_html))
                 {
                     //Parse the HTML
                     htmlWorker.Parse(sr);
                 }
             }
             doc.Close();

You need to use string interpolation.

From C# 6, string interpolation could be combined with string literals by appending "$@" to a string.

When using string interpolation, you need to contain the content that you want to reference code with "{" and "}".

If you update your string to the following, you should get the intended result:

var example_html = $@"<html>
    <body style = 'font-family: Helvetica Neue, Helvetica, Helvetica, Arial, sans-serif; text-align: center; color: #777'>;
    <div class='invoice- box'>
    <table>
     <tr class='top'>
    <td colspan=""5"">
        <table> 
           <tr> 
                <td colspan= ""3"">'{onlineTransactionViewModel.OnlineTransaction.PaymentId}' ""</br>"" ""{onlineTransactionViewModel.OnlineTransaction.PayFastReference}"" ""</br>""  ""{onlineTransactionViewModel.OnlineTransaction.PayFastReference}""
               <td class= ""title"" style = 'text - align:right'></ td >
               </ tr >
               </ table >
               </ table >
               </ div >
               </ body >
               </ html>";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM