Create N*M <table> in view by iterating through model items - asp.net-mvc

Well, easily I have a model:
#model IEnumerable<CompanyWebSite.Category>
And it's quite straightforward to iterating through its items and create a One-item-per-row table to show them.
And the problem is that I want to create a table like this:
<table>
<tr>
<td></td>
<td></td>
</tr>
//
// ...
//
<tr>
<td colspan="2"> ... LastItem ...</td>
</tr>
</table>
Seems simple, but I can't do that...!
#{
ViewBag.Title = "Products";
var last = Model.Last();
int i = 1;
}
<table id="tblCats">
#foreach(var item in Model)
{
if (i == 1){
<tr>
#(i = 2)
}
#if (!item.Equals(last))
{
<td>
<h4>#item.CategoryName</h4>
<label>#item.Description</label>
</td>
if (i == 2)
{
</tr>
i = 1;
}
else
i = 2;
}
else
{
<td colspan="2">
</td>
</tr>
}
}
Because of the first opening <tr>, Razor gets confused and doesn't see the closing }s and else statements... What can I do...?!

You could use HtmlHelper.Raw method to help razor

Related

'Object reference not set to an instance of an object' Error when trying to move contents from view page to another

I have a button in my Index.html page which shows another view page: Reports.cshtml, there is a table inside the page, now I want to remove this button and let the table showing on my Index.html page directly, but when I paste the table to the code it shows an error:
Error
Part of my view code are showed below:
<table id="hardware-data-table" class="table table-striped table-hover">
<thead bgcolor="silver">
<tr>
<th hidden="hidden">
#Html.LabelFor(model => model.Report_HardwareListByExpiration.FirstOrDefault().InvHardwareID)
</th>
<th>
#Html.LabelFor(model => model.Report_HardwareListByExpiration.FirstOrDefault().Equipment)
</th>
<th>
#Html.LabelFor(model => model.Report_HardwareListByExpiration.FirstOrDefault().HardwareModel)
</th>
<th>
#Html.LabelFor(model => model.Report_HardwareListByExpiration.FirstOrDefault().WL_EndDateFormatted)
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.Report_HardwareListByExpiration)
{
if (item.WL_EndDate < DateTime.Now && item.WL_EndDate > DateTime.Now.AddYears(-99))
{
<tr>
<td hidden="hidden">
#item.InvHardwareID
</td>
<td>
#item.Equipment
</td>
<td>
#item.HardwareModel
</td>
<td style="background-color: #ff726f">#item.WL_EndDateFormatted</td>
</tr>
}
if (item.WL_EndDate > DateTime.Now && item.WL_EndDate < DateTime.Now.AddYears(99))
{
<tr>
<td hidden="hidden">
#item.InvHardwareID
</td>
<td>
#item.Equipment
</td>
<td>
#item.HardwareModel
</td>
<td style="background-color: orange">
#item.WL_EndDateFormatted
</td>
</tr>
}
}
</tbody>
</table>
My Report controller code are showed below:
public class ReportsController : Controller
{
// GET: Report
public ActionResult Reports()
{
if (Session["UserID"] == null || !(bool)Session["IsLoggedIn"])
{
return RedirectToAction("Login", "Account");
}
ViewModel myViewModel = new ViewModel
{
User = GetSessionInfoFromSessions(),
Params = new ParametersModel
{
Start_Date = new DateTime(2015, 12, 31),
End_Date = DateTime.Now.AddDays(60)
}
};
myViewModel.Report_HardwareListByExpiration = InvHardwareModel.Report_HardwareListByExpiration(myViewModel);
return View(myViewModel);
}
And my hardware Model:
public static List<InvHardwareModel> Report_HardwareListByExpiration(ViewModel myViewModel)
{
try
{
var myAssManEnt = new AssetManagementEntities();
var myUspList = myAssManEnt.usp_Report_InvHardware_ByExpirationDates
(
agencyID : myViewModel.User.AgencyID,
deptID : myViewModel.User.DeptID,
roleID : myViewModel.User.RoleID,
startDate : myViewModel.Params.Start_Date,
endDate : myViewModel.Params.End_Date
).ToList();
var myReturnList = new List<InvHardwareModel>();
foreach(usp_Report_InvHardware_ByExpirationDates_Result myItem in myUspList)
{
myReturnList.Add(Models.InvHardwareModel.ToModel(myItem));
}
return myReturnList;
}
catch(Exception e)
{
throw ErrorHandler.MyException(e, "InvHardwareModel.Report_HardwareListByExpiration");
}
}
The code works perfect when its in the other view page, but shows exception when I move it to my home page, any ideas? Thank you so much!

Adding field to ASP.NET MVC view

I want to add one more field to my view. So basically, after displaying a town in the dropdown menu, I want to display the (*ABR) field as seen here.
As you can see from the picture, after Advance Ortopedical, I just want to add a filed called *ABR.
<table class="table datatable-responsive datatable-medical-map" id="medProviders" style="width:100%">
<thead>
<tr class="bg-info">
<th>Medical Provider (* Choose one)</th>
<th>Distance (miles)</th>
<th>Duration</th>
</tr>
</thead>
<tbody>
#{
int i = 0;
foreach (var item in medProviders)
{
<tr class="sortList" style="cursor:pointer" id="increment-#i" data-id="#item.Id" data-lat="#item.Latitude" data-long="#item.Longitude">
<td>#item.Firstname</td>
<td id="distance-#i"></td>
<td id="duration-#i"></td>
</tr>
i++;
}
}
</tbody>
</table>
<p id="medicalValidation"></p>
Any suggestions or comments on how to do this in a simple way?
Please use this code. This will add 1 more field at the end of table.
#{
int i = 0;
foreach (var item in medProviders)
{
<tr class="sortList" style="cursor:pointer" id="increment-#i" data-id="#item.Id" data-lat="#item.Latitude" data-long="#item.Longitude">
<td>
#item.Firstname
<br>*ABR</br>
</td>
<td id="distance-#i"></td>
<td id="duration-#i"></td>
</tr>
i++;
}
}
</tbody>

Make an image in a table cell into a link

I have created an e-commerce website and am using a label to display the products from my sql database, the image it shows of these products are not hyperlinks, but this is what I need them to be, I think I have written the right code but I have a "parentControl" error, could someone help plz?
Below is also a link to show you visually what is being asked. REMEMBER the picture is just an image, but needs to be a hyperlink!
private void FillPage()
{
ArrayList teesList = new ArrayList();
if (!IsPostBack)
{
teesList = ConnectionClass.GetTeesBySize("%");
}
else
{
teesList = ConnectionClass.GetTeesBySize(DropDownList1.SelectedValue);
}
StringBuilder sb = new StringBuilder();
HyperLink link = new HyperLink();
link.NavigateUrl = "http://google.com";
parentControl.Controls.Add(link);
foreach (Tees tees in teesList)
{
sb.Append(string.Format(#"<table class='TeesTable'>
<tr>
<th rowspan='1' width='150px'><img runat='server' src='{6}' /</th>
<th width='50px'>Name: </th>
<td>{0}</td>
</tr>
<tr>
<th>Size:</th>
<td>{1}</td>
</tr>
<tr>
<th>Price:</th>
<td>{2}</td>
</tr>
</table>",
tees.name, tees.size, tees.price, tees.id, tees.id, tees.id, tees.image));
LblOutput.Text = sb.ToString();
(https://dl-web.dropbox.com/get/CompetitiveStreakTemplate/Pic.png?_subject_uid=9403629&w=AAD63dzqPQcNMNSU0OwbVBrGjNGFvtt7VWJ6DKwlu4UoPw).
You need to close your <img> tag properly and wrap it in a <a> to make it a hyperlink. Also use <td> instead of <th> for data rows and not headers.
Something a bit more like:
<td rowspan='1' width='150px'>
<a href='{0}.aspx'>
<img runat='server' src='{6}' />
</a>
</td>
You should probably also tidy up the rest of the code appended to your table, checking what is a header or data, and using a <tbody> tag inside the <table>
Edit: looking closer it seems as though you aren't creating the table properly in the first place, change this chunk of your code to do the loop properly:
parentControl.Controls.Add(link);
sb.Append("<table class='TeesTable'><tbody>");
foreach (Tees tees in teesList)
{
sb.Append(string.Format(#"
<tr>
<td rowspan='1' width='150px'>
<a href='{0}.aspx'>
<img runat='server' src='{6}' />
</a>
</td>
<td width='50px'>Name: </td>
<td>{0}</td>
</tr>
<tr>
<td>Size:</td>
<td colspan='2'>{1}</td>
</tr>
<tr>
<td>Price:</td>
<td colspan='2'>{2}</td>
</tr>",
tees.name, tees.size, tees.price, tees.id, tees.id, tees.id, tees.image));
}
sb.Append("</tbody></table>");
LblOutput.Text = sb.ToString();

mvc view table row number counter

I have a table than shown one record of my model. for example list of category.
i want to create manually row number for this table.
<table class="table table-striped table-bordered table-hover table-full-width dataTable">
#foreach (var item in Model)
{
<tr>
<td>
**I want to Show Row Number Here**
</td>
<td>
#Html.ActionLink(item.Name, "ViewSubCategory", "ProductSubCategory", new { id = item.Id }, null)
</td>
</tr>
}
</table>
Define a counter rowNo and write
#{ int rowNo = 0; }
#foreach (var item in Model) {
<tr style="background: #classtr;" >
<td>
#(rowNo += 1)
</td>
Define a counter rowNo and write
<table class="table table-striped table-bordered table-hover table-full-width dataTable">
#{int rowNo;}
#foreach (var item in Model)
{
<tr>
<td>
#rowNo++;
</td>
<td>
#Html.ActionLink(item.Name, "ViewSubCategory", "ProductSubCategory", new { id = item.Id }, null)
</td>
</tr>
}
</table>
None of the above worked for me - I did this:
#{int RowNo = 0;}
#foreach (var item in Model) {
<tr>
<td>#{RowNo++;} #RowNo</td>
You may use the Select overload:
<table class="table table-striped table-bordered table-hover table-full-width dataTable">
#foreach (var item in Model.Select((item,index)=>new{item,index})
{
<tr>
<td>
#item.index
</td>
<td>
#Html.ActionLink(item.item.Name, "ViewSubCategory", "ProductSubCategory", new { id = item.item.Id }, null)
</td>
</tr>
}
</table>
I've found the next option for my ASP.Net MVC project. All above options didn't work for my project.
#foreach (var item in Model.Select((x, i) => new { Data = x, Index = i + 1 }))
{
<tr>
<td>
#item.Index
</td>
<td>
#Html.DisplayFor(modelItem => item.Data.ReviewerName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Data.ReviewerComments)
</td>
<td>
#Html.DisplayFor(modelItem => item.Data.ReviewerRating)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.Data.Id })
</td>
</tr>
}
I think this code will solve the problem
let rows = document.querySelectorAll('tr');
rows.forEach((row) => {
let z = document.createElement("td");
z.textContent = `(row #${row.rowIndex})`;
row.appendChild(z);
});
<table>
<thead>
<tr><th>Item</th> <th>Price</th></tr>
</thead>
<tbody>
<tr><td>Bananas</td> <td>$2</td></tr>
<tr><td>Oranges</td> <td>$8</td></tr>
<tr><td>Top Sirloin</td> <td>$20</td></tr>
</tbody>
<tfoot>
<tr><td>Total</td> <td>$30</td></tr>
</tfoot>
</table>
Easiest approach is to use CSS to have the row numbers in your tables in the index of you MVC View.
.css-serial {
counter-reset: serial-number;
/* Set the serial number counter to 0 */
}
.css-serial td:first-child:before {
counter-increment: serial-number+1;
/* Increment the serial number counter */
content: counter(serial-number);
/* Display the counter */
}
table{
font-family: Arial;
border:solid;
border-width:1px;
border-color:#dedede;
border-radius:5px;
}
th{
background-color:#efefef;
}
td{
padding:3px;
margin:3px;
}
<table class="css-serial">
<tr>
<th>Row #</th>
<! –– Row Number goes here automatically with CSS style ––>
<th>Name</th>
</tr>
<tr>
<td></td>
<td>John</td>
</tr>
<tr>
<td></td>
<td>Richard</td>
</tr>
<tr>
<td></td>
<td>Joe</td>
</tr>
<tr>
<td></td>
<td>Rogan</td>
</tr>
<tr>
<td></td>
<td>Lebron</td>
</tr>
<tr>
<td></td>
<td>Marcus</td>
</tr>
<tr>
<td></td>
<td>Jane</td>
</tr>
<tr>
<td></td>
<td>Maria</td>
</tr>
</table>

Insert "where" rule in a "foreach" search

I need some help in order to put a where rule into the foreach search. My goal is to exclude orders where the customerOrder.ERPOrderNumber starts with letter E
The code that i have returns all the orders for the specific customer.
Thank you in advance for your help.
#foreach (var customerOrder in Model.CustomerOrders)
{
<tr>
<td class="mavo-order-date">#customerOrder.OrderDate.ToShortDateString()
</td>
<td class="mavo-status">#customerOrder.Status
</td>
<td class="mavo-order-number">
#customerOrder.OrderNumber
</td>
#if (Model.ShowErpOrderNumber)
{
<td class="mavo-erp-order">#customerOrder.ERPOrderNumber
</td>
}
<td class="mavo-po">#customerOrder.CustomerPO
</td>
<td class="mavo-order-total">#customerOrder.OrderGrandTotal.ToCurrency()
</td>
<td class="mavo-view">
<a class="btn btnStyleA tbm5" href="#Url.Action("OrderHistoryDetail", "Account", new { orderId = customerOrder.ERPOrderNumber })">View Details</a>
</td>
</tr>
}
You can put an if statement inside the foreach loop to only write out the table row when the order number doesn't start with the letter E.
#foreach (var customerOrder in Model.CustomerOrders)
{
#if(!customerOrder.ERPOrderNumber.StartsWith("E"))
{
// Markup goes in here
}
}
Or you can use LINQ to filter the CustomerOrders collection.
#foreach(var customerOrder in Model.CustomerOrders.Where(x => !x.StartsWith("E"))

Resources