C# For each loop in a a table? - c#

I'm trying to display various information with the help of a for each loop.
I've created a for each loop, that iterates through a list of item. In this list there is another list of items.
As for now it's displayed like this:
My code is:
#foreach (Invoice invoice in ViewBag.Invoices)
{
<table>
<tr>
<th>Customer</th>
<th>Product</th>
<th>Quantity</th>
<th>Price</th>
<th>Total Price</th>
</tr>
#foreach (OrderItem orderItem in invoice.OrderItems)
{
<tr>
<td>#invoice.Customer.Firstname #invoice.Customer.Lastname</td>
<td>#orderItem.Product.Title </td>
<td>#orderItem.Quantity </td>
<td>#orderItem.Product.Price </td>
<td>#orderItem.TotalPrice</td>
</tr>
}
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td class="border-top">#invoice.TotalPrice</td>
</tr>
</table>
}
However, I don't want it to display the customers name twice. And I don't want to have the customer on its own row. Therefore I tried to put the starting tag along with the customer outside of the foreach loop, and instead ending the foreach loop with a <tr> tag. So it'd look like this:
#foreach (Invoice invoice in ViewBag.Invoices)
{
<table>
<tr>
<th>Customer</th>
<th>Product</th>
<th>Quantity</th>
<th>Price</th>
<th>Total Price</th>
</tr>
<tr>
<td>#invoice.Customer.Firstname #invoice.Customer.Lastname</td>
#foreach (OrderItem orderItem in invoice.OrderItems)
{
<td>#orderItem.Product.Title </td>
<td>#orderItem.Quantity </td>
<td>#orderItem.Product.Price </td>
<td>#orderItem.TotalPrice</td>
</tr>
<tr>
}
<td></td>
<td></td>
<td></td>
<td></td>
<td class="border-top">#invoice.TotalPrice</td>
</tr>
</table>
}
UPDATED SOLUTION
I followed the wise words of #Ed Plunkett and initialized a local string to null. The I created an if/else statement to check if the previous customer has been set, and initialized the value of the previous customer in the end of the loop.
#{string prevCust = null; }
#foreach (Invoice invoice in ViewBag.Invoices)
{
<table>
<tr>
<th>Customer</th>
<th>Product</th>
<th>Quantity</th>
<th>Price</th>
<th>Total Price</th>
</tr>
#foreach (OrderItem orderItem in invoice.OrderItems)
{
<tr>
#if (prevCust != invoice.Customer.Firstname + invoice.Customer.Lastname)
{
<td>#invoice.Customer.Firstname #invoice.Customer.Lastname</td>
}
else
{
<td></td>
}
<td>#orderItem.Product.Title </td>
<td>#orderItem.Quantity </td>
<td>#orderItem.Product.Price </td>
<td>#orderItem.TotalPrice</td>
</tr>
prevCust = invoice.Customer.Firstname + invoice.Customer.Lastname;
}
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td class="border-top">#invoice.TotalPrice</td>
</tr>
</table>
}

I'd do it caveman style: Just make a local variable String prevCustomerName, initialize to null, and update it at the end of the loop block. At the beginning of the loop block, if the new customer name is the same as prevCustomerName, don't insert it into the HTML for that row.
I enjoyed your original code with </tr>\n<tr> in the inner loop, but it took me a minute to figure out what you were doing, and Razor seems to be totally baffled. And you still need to ugly it up with a special case to add an empty cell on non-first rows. If you're stuck putting in an if either way, do the caveman.

When resorting to iteration in a table, it's helpful (even for yourself, not just for razor or whatever view engine you are using) to keep it as structured and simple as possible.
(the comments on your question should be enough explanation as to why this is a good idea)
try using multiple tr's per invoice to achieve your goals. for example :
#foreach (Invoice invoice in ViewBag.Invoices)
{
<table>
<tr>
<th>Customer</th>
<th>Product</th>
<th>Quantity</th>
<th>Price</th>
<th>Total Price</th>
</tr>
<tr>
<td colspan="4">#invoice.Customer.Firstname #invoice.Customer.Lastname</td>
</tr>
#foreach (OrderItem orderItem in invoice.OrderItems)
{
<tr>
<td>#orderItem.Product.Title </td>
<td>#orderItem.Quantity </td>
<td>#orderItem.Product.Price </td>
<td>#orderItem.TotalPrice </td>
</tr>
}
<tr>
<td colspan="4"></td>
<td class="border-top">#invoice.TotalPrice</td>
</tr>
</table>
}
You could even resort to generating one table per invoice if that helps make things simpler for you.

Without being ASP-expert I suppose you have to handle the first row differently then the others :
<tr>
<td>#invoice.Customer.Firstname #invoice.Customer.Lastname</td>
<td>#orderItem.Product.Title </td>
<td>#orderItem.Quantity </td>
<td>#orderItem.Product.Price </td>
<td>#orderItem.TotalPrice </td>
</tr>
Now handle the rest in the loop omitting the first (already handled) element:
#foreach (OrderItem orderItem in invoice.OrderItems.Skip(1))
{
<tr>
<td/>
<td>#orderItem.Product.Title </td>
<td>#orderItem.Quantity </td>
<td>#orderItem.Product.Price </td>
<td>#orderItem.TotalPrice </td>
</tr>
}
A more generic approach would be using a for-loop with an index and check if you´re handling the first element:
#for(int i = 0; invoice.OrderItems.Count; i++)
{
<tr>
<td>#(i != 0 ? invoice.Customer.Firstname + " " + invoice.Customer.Lastname : "")</td>
<td>#invoice.OrderItems[i].Product.Title </td>
<td>#invoice.OrderItems[i].Quantity </td>
<td>#invoice.OrderItems[i].Product.Price </td>
<td>#invoice.OrderItems[i].TotalPrice </td>
</tr>
}
However I´m not sure if this is even valid ASP-syntax.

Related

HtmlAgilityPack multiple tbody in table

There are multiple Tbodies in a table and I am trying to parse them out by using HTMLagilitypack. Normally the code below would work but it doesn't. Right now it only prints the first tbody and ignores the 2nd.
Code
var tableOffense = doc.DocumentNode.SelectSingleNode("//table[#id='OFF']");
var tbody = tableOffense.SelectNodes("tbody");
foreach(var bodies in tbody)
{
Console.WriteLine("id "+offender.offenderId +" "+ Utilities.RemoveHtmlCharacters(bodies.InnerText));
}
HTML
<table id="OFF" class="centerTable" cols="2" style="margin-top:0; width:100%;" cellpadding="0" cellspacing="0">
<tbody>
<!-- %%$SPLIT -->
<tr> <th id="offenseCodeColHdr" scope="row" style="width:25%;" class="uline">Offense Code</th> <td headers="offenseCodeColHdr" class="uline">288(a)</td> </tr> <tr> <th id="descriptionColHdr" scope="row" style="width:25%;" class="uline">Description</th> <td headers="descriptionColHdr" class="uline">LEWD OR LASCIVIOUS ACTS WITH A CHILD UNDER 14 YEARS OF AGE</td> </tr> <tr> <th id="lastConvictionColHdr" scope="row" style="width:25%;" class="uline">Year of Last Conviction</th> <td headers="lastConvictionColHdr" class="uline"> </td> </tr> <tr> <th id="lastReleaseColHdr" scope="row" style="width:25%;" class="uline">Year of Last Release</th> <td headers="lastReleaseColHdr" class="uline"> </td> </tr>
<tr><th colspan="2"><hr style="height:2px;background-color:#000;"></th></tr> </tbody>
<!-- %%$SPLIT -->
<tbody><tr> <th id="offenseCodeColHdr" scope="row" style="width:25%;" class="uline">Offense Code</th> <td headers="offenseCodeColHdr" class="uline">261(a)(2)</td> </tr> <tr> <th id="descriptionColHdr" scope="row" style="width:25%;" class="uline">Description</th> <td headers="descriptionColHdr" class="uline">RAPE BY FORCE OR FEAR</td> </tr> <tr> <th id="lastConvictionColHdr" scope="row" style="width:25%;" class="uline">Year of Last Conviction</th> <td headers="lastConvictionColHdr" class="uline"> </td> </tr> <tr> <th id="lastReleaseColHdr" scope="row" style="width:25%;" class="uline">Year of Last Release</th> <td headers="lastReleaseColHdr" class="uline"> </td> </tr>
<tr><th colspan="2"><hr style="height:2px;background-color:#000;"></th></tr> </tbody>
<!-- %%$SPLIT -->
</table>
I've printed just the tableOffense node by itself to make sure the 2nd tbody exists at load and it does.
Question
Why does the code only print out the first tbody and not both?
I haven't figured out why your code only gives you one tbody, but may I suggest an alternative solution, to select all your <tbody> elements?
Personally I would make use of XPAth and just select all tbody elements in one go, without an additional SelectNodes():
var tbody = doc.DocumentNode.SelectNodes("//table[#id='OFF']//tbody");
foreach (var elem in tbody)
{
//Dump only works in LinqPad
elem.InnerText.Dump();
}
Edit:
The following code (your code) also yields the same results
var tableOffense = doc.DocumentNode.SelectSingleNode("//table[#id='OFF']");
var tbody = tableOffense.SelectNodes("//tbody");

MVC Printing out each Enum value through #foreach

Enum:
public enum Enumenter
{
Products = 10,
Users = 20,
Actions = 30
}
my view:
#model IEnumerable<ServerDB.Tables.EntityType>
#{
ViewBag.Title = "Infrastruktur";
}
<table class="table">
<tr>
<th>
<h2>Infrastruktur</h2>
</th>
<th></th>
</tr>
#foreach (var val in Enum.GetNames(typeof(ServerDB.Tables.Enum)))
{
<tr>
<td>
#Html.DisplayName((String.Format("{0}{1}", val, "2")))
</td>
<td></td>
<td>
<p>
</p>
</td>
<td></td>
</tr>
}
#foreach (var Ost in Enum.(typeof(ServerDB.Tables.Enum)))
{
#Html.DisplayName((String.Format("{0}", Ost)))
}
</table>
How do i Print out The values next to the products?
im going to use the numbers from the enum to make a query search, so i can search for any product, any users or actions for that matter.
im no expert in this, so please be gentle.
Enum.GetValues returns values for the enum as objects, so you need to cast them to int value (using int instead of var will do that for you). After that you can use Enum.GetName to get the name for specific value:
#foreach (int val in Enum.Values(typeof(ServerDB.Tables.Enum)))
{
var name = Enum.GetName(typeof(ServerDB.Tables.Enum), val);
<tr>
<td>
#Html.DisplayName((String.Format("{0}{1}", name, "2")))
</td>
<td>
#val
</td>
<td>
<p>
</p>
</td>
<td>
</td>
</tr>
}
There is another approach which doesn't use the Enum.GetName method. You simply cast the value you get from Enum.Values to string to get the name and to int to get the value
#foreach (var name in Enum.Values(typeof(ServerDB.Tables.Enum)))
{
var val = (int)name;
<tr>
<td>
#Html.DisplayName((String.Format("{0}{1}", name, "2")))
</td>
<td>
#val
</td>
<td>
<p>
</p>
</td>
<td>
</td>
</tr>
}

Creating a table programmatically

I have been searching for quite some time to create the following table through code-behind using C#. I am finding difficulty in adding a <tr> to <thead> and <tr> to <tbody>. This is how the table should look like:
<table id="mytable" border="1" cellpadding="10" cellspacing="0" >
<caption>myCaption</caption>
<thead>
<tr>
<td> </td>
<th scope="col">myHeader1</th>
<th scope="col">myHeader2</th>
<th scope="col">myHeader3</th>
</tr>
</thead>
<tbody>
<tr>
<td>2</td>
<td>3</td>
<td>1</td>
</tr>
</tbody>
</table>
Any help is appreciated.
Create a strongly typed view with a list of whatever you're binding, and use the #foreach loop:
#model List<MyClass>
<table id="mytable" border="1" cellpadding="10" cellspacing="0" >
<caption>myCaption</caption>
<thead>
<tr>
<td> </td>
<th scope="col">myHeader1</th>
<th scope="col">myHeader2</th>
<th scope="col">myHeader3</th>
</tr>
</thead>
<tbody>
#foreach(var m in Model)
{
<tr>
<td>#m.MyProp1</td>
<td>#m.MyProp2</td>
<td>#m.MyProp3</td>
</tr>
}
</tbody>
I have done similar thing using C# MVC. Here is a sample code. Hope this will help to get an idea.
#{int count = Model.HeadingsList.Count;}
<table>
<thead>
<tr>
#foreach (string heading in Model.HeadingsList)
{
<th>#heading</th>
}
</tr>
</thead>
<tbody>
#foreach (string row in Model.rowsList)
{
string[] cellValues = Array.ConvertAll(row.Split(','), p => p.Trim());
if (count != cellValues.Count()) { return; }
<tr>
#for (int i = 0; i < #count; i++)
{
<td>#cellValues[i]</td>
}
</tr>
}
</tbody>
</table>
I had a list of rows like below.
Array[0]['cell1','cell2','cell3'...]
Array[1]['cell1','cell2','cell3'...]

add edit table, how to change a row to edit mode?

Below is my razor code for my table of users and the current add/edit layout
<table class="smalltable" cellpadding="0" cellspacing="0" id="tblUsers">
<thead>
<tr>
<th> </th>
<th>First Name</th>
<th>Last Name</th>
<th>Dept</th>
<th>Assyst Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>#{ Html.BeginForm("AddEditUser", "Home"); }
<input type="submit" value="Add" id="btnSave" name="cmd" class="plain-button" />
</td>
<td>#Html.Editor("Forename")</td>
<td>#Html.Editor("Surname")</td>
<td>#Html.DropDownList("lstDepts")</td>
<td>#Html.Editor("AssystName")
#{ Html.EndForm(); }</td>
</tr>
#foreach (var User in Model)
{
<tr>
<td>#Html.ActionLink("Edit", "AddEditUser", new { id = User.ID }, new { name = "cmd", value = "Edit" })</td>
<td>
#User.Forename
</td>
<td>
#User.Surname
</td>
<td>
#User.Dept
</td>
<td>
#User.AssystName
</td>
</tr>
}
</tbody>
</table>
What i want to achieve is when a edit is pressed, the row that the edit link was on turns into edit boxes, i how to load up the add form with the edit users details (i could use hidden id and set it with querystring) but i wanted to edit in place really
anyone know how to do this or can point me in the right place?
THanks

Adding rows to the final page of a pagedlist

<div>
<table ​>
<tr>
<th>Customer ID</th>
<th>Name</th>
<th>Type</th>
</tr>
#foreach (var a in Model.Attachments)
{
<tr>
<td>
#a.CId
</td>
<td>
#a.CName
</td>
<td>
#a.CType
</td>
</tr>
}
</table>
#Html.PagedListPager((IPagedList)Model.Attachments, page => Url.Action("Index", new { page }))
</div>
Currently I am displaying 25 items per page. If the final page does not have 25 items, I want to append rows to the end of the table, to keep the Page selector at the same level from page to page.
This seems like it would work, I just don't know where to put it:
#for (int i = 25; i > Model.Attachments.Count() % 25; i--)
{
<tr>
<td></td>
</tr>
}
You have for sure a loop thrown the attachments list.
Put this loop right after the loop where you write your TRs.
Just take into account that if your data makes your TRs higher, this will break your solution. Other thing you may try is adding a HTML space in your dummy rows:
<div>
<table ​>
<tr>
<th>Customer ID</th>
<th>Name</th>
<th>Type</th>
</tr>
#foreach (var a in Model.Attachments)
{
<tr>
<td>
#a.CId
</td>
<td>
#a.CName
</td>
<td>
#a.CType
</td>
</tr>
}
#for (int i = 25; i > Model.Attachments.Count() % 25; i--)
{
<tr>
<td></td>
</tr>
}
</table>
#Html.PagedListPager((IPagedList)Model.Attachments, page => Url.Action("Index", new { page }))
</div>

Categories

Resources