I am trying to create a POST endpoint where on success, it will send a HTML email with the POST data.
JSON data that I am trying to iterate on:
{
"Submitter":[
{
"Obj1":[
"test",
"test2"
]
},
{
"Obj2":[
"test3",
"test4"
]
}
]
}
TestingController:
public class Testing2Controller : ControllerBase
{
public class Submitter
{
public List<string> Obj1 { get; set; }
public List<string> Obj2 { get; set; }
}
public class MyData
{
public List<Submitter> Submitter { get; set; }
}
public string POST([FromBody] MyData data)
{
string composeTableObj1 = @"";
string composeTableObj2 = @"";
foreach (var item in data.Submitter)
{
if (item.Obj1 != null)
{
foreach (var objItem in item.Obj1)
{
composeTableObj1 = $"<tr><td>{objItem}</td></tr>";
}
}
if (item.Obj2 != null)
{
foreach (var objItem in item.Obj2)
{
composeTableObj2 = $"<tr><td>{objItem}</td></tr>";
}
}
}
string body = @$"<table>
<thead>
<tr>
<th>Object 1</th>
<th>Object 2</th>
</tr>
</thead>
<tbody>
{composeTableObj1}
{composeTableObj2}
</tbody>
</table>
";
return body;
}
}
Result of the above:
| Object 1 | Object 2 |
|----------|----------|
| Test | |
| Test 2 | |
| Test 3 | |
| Test 4 | |
Desired Result:
| Object 1 | Object 2 |
|----------|----------|
| Test | Test 3 |
| Test 2 | Test 4 |
The HTML table will then be compiled into a bigger HTML body which will then be sent out as an email but im unsure how I can achieve the desired result above.
TIA
CodePudding user response:
try this
<tbody>
<tr>
<th>{composeTableObj1}</th>
<th>{composeTableObj2}</th>
</tr>
</tbody>
CodePudding user response:
Currently you are just adding rows inside same columns inside your c# loop, you should do the following instead and using single variable you can achieve that and append html into a string. Also added a case where you may have no data at all so you can show the cell as empty data or whatever you like
foreach (var item in data.Submitter)
{
composeTableObj1 = $"<tr>" //start row tag
//Column 1 Obj1 data
if (item.Obj1 != null)
{
foreach (var objItem in item.Obj1)
{
composeTableObj1 = $"<td>{objItem}</td>";
}
}
else {
composeTableObj1 = $"<td>Empty Data</td>";
}
//Column 2 Obj2 data
if (item.Obj2 != null)
{
foreach (var objItem in item.Obj2)
{
composeTableObj1 = $"<td>{objItem}</td>";
}
}
else {
composeTableObj1 = $"<td>Empty Data</td>";
}
composeTableObj1 = $"</tr>" //end row tag
}