2

I have an html template to send emails. How can i get the table tag and inject dynamically all rows?

html template:

Hello {Username}!

<table class="tblCss">
 <tr>
  <th> Name </th>
  <th> Age </th>
 </tr>
 </table>

cs file

string body = string.Empty;  
using(StreamReader reader = new StreamReader("HtmlTemplate.html")))  
{  
  body = reader.ReadToEnd();  
}  

body = body.Replace("{Username}", "test"); 
  • You are not doing it wrong. But you don´t have {Username} on your sample HTML – NicoRiff Mar 01 '17 at 23:08
  • That looks like you are trying to build your own html view rendering engine. Are you able to change the template or the code or either? – Tim Mar 01 '17 at 23:09
  • Can you change the template? is it just name and age? Where do you store the values for rows? What have you tried so far? – xszaboj Mar 01 '17 at 23:11
  • Yes, i can change the template. Exist more columns in table (it was only an example). The values are populated in code behind (c#) from database (list objects) –  Mar 01 '17 at 23:14

1 Answers1

1

Here is my own suggestion. IF you are using MVC, create an independent view for your emails (let's say myemail.cs) and assign a model to it (myemailModel).

Here is your myemailModel class

public class myemailModel {
   public string Username{get;set;}
   public IList<Data> data{get;set;}
   public class Data{
      public string Name{get;set;}
      public int Age{get;set;}

   }
}

So your view would look like this:

@model myemailModel

<html>
<body>
Hello @Model.Email!

@if (Model.data !=null && Model.data.count() >0)
{


  <table class="tblCss">
    <tr>
    <th> Name </th>
    <th> Age </th>
   </tr>
   foreach (var i in Model.data)
  {
      <tr>
        <td>@i.Name</td>
        <td>@i.Age</td>
      </tr>
   }
 </table>


}


</body>

</html>

Finally, you need to render the view into a string. Use the following method (Render a view as a string):

 public string RenderRazorViewToString(string viewName, object model)
 {
   ViewData.Model = model;
   using (var sw = new StringWriter())
   {
     var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext,
                                                         viewName);
      var viewContext = new ViewContext(ControllerContext, viewResult.View,
                             ViewData, TempData, sw);
     viewResult.View.Render(viewContext, sw);
     viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
    return sw.GetStringBuilder().ToString();
  }
}

And call the above method to get the body:

 string body = RenderRazorViewToString("myemail", new myemailModel { 
       Username="foo", 
          data = new List<myemailModel>{
            // fill it 
          }
      });
Community
  • 1
  • 1
Amir H. Bagheri
  • 1,416
  • 1
  • 9
  • 17