Programmatically start new TableRow in table - c#

I am trying to load models and set every model in a separate, <td> when I reach 5 <td> I want to automatically start a new <tr> but it isn't really working with an if statement. Is it possible or should I go for an entire different approach?
Here is my code:
<tr>
#for (int i = 0; i < Model.Count; i++)
{
<td>
<img width="200px" src="#Url.Action("GetImage", "Beheer", new { productId = Model[i].product_id }) " alt="pasfoto"/><br />
<center><b>#Html.ActionLink(Model[i].naam, "PrProduct", "Categorie", new { id = Model[i].product_id }, null)</b></center>
<center>€ #Html.Label(Model[i].prijs)</center>
</td>
}
</tr>

Use the modulo operator %. Each time i%5 == 0, print a row around the td
#for (int i = 0; i < Model.Count; i++)
{
#if(i%5 == 0)
{
<tr>
}
<td>
<img width="200px" src="#Url.Action("GetImage", "Beheer", new { productId = Model[i].product_id }) " alt="pasfoto"/><br />
<center><b>#Html.ActionLink(Model[i].naam, "PrProduct", "Categorie", new { id = Model[i].product_id }, null)</b></center>
<center>€ #Html.Label(Model[i].prijs)</center>
</td>
#if(i%5 == 0)
{
</tr>
}
}
So you're going to have a table row when i is 0, 5, 10, 15, etc.

#for (int i = 0; i < Model.Count; i++)
{
#if(i%5 == 0)
{
<tr></tr>
}
<td>
<img width="200px" src="#Url.Action("GetImage", "Beheer", new { productId = Model[i].product_id }) " alt="pasfoto"/><br />
<center><b>#Html.ActionLink(Model[i].naam, "PrProduct", "Categorie", new { id = Model[i].product_id }, null)</b></center>
<center>€ #Html.Label(Model[i].prijs)</center>
</td>
}
The above code worked for me. Is it not much different from the answer Havelock gave, but it will not close the brackets in the above code if you do not close the html tags within the same if statement. This way may not look as good if you use borders because I think it will display one empty row? But, for me this worked fine:)

Related

Out of stock message passed to View If quantity <= 0

The problem is that if i have 2 items in cart that do not have the desired amount in stock, it will show only a message for one of them. Also i do not know how i can pass the information at catch{} part. Can someone please point me in the right direction, i am relatively new to asp.net mvc and programming in general.
There is a constraint in db to check quantity >= 0
Controller
public ActionResult CreateOrder()
{
List<ItemViewModel> cart = (List<ItemViewModel>)Session["cart"];
Check check = new Check();
decimal s = 0;
foreach (var item in cart)
{
var device = db.Devices.Single(d => d.DeviceID == item.Device.DeviceID);
if (device.Quantity <= 0)
{
TempData["Message"] = string.Format("Out of stock for {0}. In stock: {1}. ", device.DeviceName, device.Quantity);
return View("Cart");
}
device.Quantity -= item.Quantity;
check.DateTime = DateTime.Now;
check.CustomerName = User.Identity.Name;
s = s + item.Device.Price.Value * item.Quantity;
check.Device += item.Device.DeviceName + " x " + item.Quantity + " - $" + (item.Device.Price *= item.Quantity) + ", " ;
}
check.Total = (int)s;
check.Tax = check.Total * 20 / 100;
try
{
db.Checks.Add(check);
db.SaveChanges();
foreach (var item in cart.ToList())
{
cart.Remove(item);
}
}
catch (DbUpdateException)
{
TempData["Message"] = TempData;
return View("Cart");
}
if (User.IsInRole(RoleName.Admin))
{
return RedirectToAction("Details", "Checks", new { id = check.CheckID });
}
return RedirectToAction("PurchaseDetails", "Checks", new { id = check.CheckID });
}
View
#{
ViewBag.Title = "Cart";
}
#using WebShop.ViewModels;
<h2>Cart</h2>
<br />
#using (#Html.BeginForm("Update", "Devices", FormMethod.Post))
{
<div class="col-lg-12 col-md-12 col-sm-12">
<table class="table table-bordered table-hover" cellpadding="2" cellspacing="2" border="1">
<thead>
<tr>
<th width="5%"></th>
<th>Device</th>
<th width="7%">Price</th>
<th width="7%">Quantity</th>
<th width="7%">Total</th>
<th width="9%"></th>
</tr>
</thead>
<tbody>
#{
decimal s = 0;
decimal total = 0;
int index = 1;
decimal one = 0;
}
#foreach (ItemViewModel item in (List<ItemViewModel>)Session["cart"])
{
s = s + item.Device.Price.Value * item.Quantity;
one = item.Device.Price.Value;
total = item.Device.Price.Value * item.Quantity;
<tr>
<td><img src="#item.Device.Image" width="50" height="50" /></td>
<td>#item.Device.DeviceName</td>
<td>$#one.ToString("n2")</td>
<td><input class="form-control" type="text" name="quantity" value="#item.Quantity" style="width: 50px"></td>
<td>
$#total.ToString("n2")
#{index++;}
</td>
<td>
<button type="button" class="btn btn-bitbucket" onclick="location.href='#Url.Action("Remove", "Devices", new { id = item.Device.DeviceID })'">
<i class="fa fa-remove"></i>
</button> |
<button type="submit" class="btn btn-bitbucket">
<i class="fa fa-refresh"></i>
</button>
</td>
</tr>
}
<tr>
<td align="right" colspan="4">Total:</td>
<td>$#s.ToString("n2")</td>
</tr>
</tbody>
</table>
</div>
}
<br />
<button class="btn btn-bitbucket" type="button" onclick="location.href='#Url.Action("Shop", "Devices")'">Continue shoping</button>
<button class="btn btn-bitbucket" type="button" onclick="location.href='#Url.Action("CreateOrder", "Devices")'">Create order</button> | #TempData["Message"]
Thanks mjwills for the problem location :)
Do not know if this is the best solution but it's working so i am happy with it.
if (device.Quantity <= 0)
{
foreach (var outOfStockItem in cart)
{
string messages = string.Format("Out of stock for {0}. In stock: {1}. | ", outOfStockItem.Device.DeviceName, outOfStockItem.Device.Quantity);
TempData["Messages"] += messages;
}
return View("Cart");
}
Cart Image

asp.net paramter always null

I have a problem with my asp.net app. This is my index.html
#using BricksBreaking;
#model FieldModel
#{
ViewData["Title"] = "Game";
}
<h2>Index</h2>
<table class="field">
#for (int row = 0; row < Model.Field.RowCount; row++)
{
<tr>
#for (int column = 0; column < Model.Field.ColumnCount; column++)
{
var tile = Model.Field.Tiles[row, column];
if (tile == null)
{
<td />
}
else
{
if (Model.Field.Tiles[row, column].Color == TileColor.Red) {
<td>
<a href='/BricksBreaking/Click?r=#row?c=#column'>
<img src='/images/cervena.png' />
</a>
</td>
}if(Model.Field.Tiles[row, column].Color == TileColor.Yellow)
{
<td>
<a href='/BricksBreaking/Click?r=#row?c=#column'>
<img src='/images/zlta.png' />
</a>
</td>
}if(Model.Field.Tiles[row, column].Color == TileColor.Blue)
{
<td>
<a href='/BricksBreaking/Click?r=#row?c=#column'>
<img src='/images/modra.png' />
</a>
</td>
}
}
}
</tr>
}
</table>
And this is my controller
public class BricksBreakingController : Controller
{
ScoreServiceDatabase scoreService = new ScoreServiceDatabase();
public IActionResult Index()
{
var field = new Field(9, 9, 5);
HttpContext.Session.SetObject("field", field);
var model = new FieldModel
{ Field = field, Scores = scoreService.GetTopScores() };
return View(model);
}
public IActionResult Click(int r, int c)
{
var field = HttpContext.Session.GetObject("field") as Field;
field.ClickTile(r,c);
HttpContext.Session.SetObject("field", field);
var model = new FieldModel
{ Field = field, Scores = scoreService.GetTopScores() };
return View("Index", model);
}
}
}
Problem is. that always here at this line
<a href='/BricksBreaking/Click?r=#row?c=#column'>
Arguments passed to Function Click in controller are always 0. No matter if i write something like this
<a href='/BricksBreaking/Click?r=2?c=2'>
There will be always 0.
Can somebody help me with this? I am new to .NET.
You only need to write a ? before the first parameter. Every parameter after the first needs a &
<a href='/BricksBreaking/Click?r=2&c=2'>

Allowing screen reader to read Kendo UI Chart data

The website I'm developing needs to comply with the WCAG 2.0 guidelines, meaning a person should be able to access all information on the site using a screen reader. Since it's a BI dashboard making heavy use of Kendo Charts it failed the test.
I need a way for screen readers to be able to read the Kendo Charts on my website, while reusing the chart's datasource.
I solved this by automatically generating a table for each chart on the page.
Create partial view which generates HTML table
#{
var divId = Guid.NewGuid().ToString();
var tableId = Guid.NewGuid().ToString();
var templateId = Guid.NewGuid().ToString();
}
/* Chart ID */
#model string
<div id="#divId" class="hiddenTable"></div>
<script>
(function () {
var template = kendo.template($("##templateId").html());
var chartData = $("##Model").data("kendoChart").dataSource;
$("##divId").prepend(template(chartData.data()));
})();
</script>
<script id="#templateId" type="text/x-kendo-tmpl">
# var columnNames = Chart.getColumnNamesFromData(data) #
<table id="#tableId">
<thead>
<tr>
# for(var columnIndex = 0; columnIndex < columnNames.length; columnIndex++) { #
<th scope="col">#= S(columnNames[columnIndex]).humanize().s #</th>
# } #
</tr>
</thead>
<tbody>
# for(var i = 0, len = data.length; i < len; i++) { #
# if (data[i][columnNames[0]] != undefined) { #
<tr>
# for(var columnIndex = 0; columnIndex < columnNames.length; columnIndex++) { #
# if(columnNames[columnIndex] == 'Date') { #
<th scope="row">#= kendo.toString(data[i][columnNames[columnIndex]], "MMMM yyyy") #</th>
#} else { #
<td>#= kendo.toString(data[i][columnNames[columnIndex]] != undefined ? data[i][columnNames[columnIndex]] : 0, "n1") #</td>
# } #
# } #
</tr>
# } #
# } #
</tbody>
</table>
</script>
Add CSS to hide table from view
.hiddenTable {
position: absolute;
left: -10000px;
top: auto;
width: 1px;
height: 1px;
overflow: hidden;
}
Add img role to chart
#(Html.Kendo().Chart<MyModel>()
.Name(Guid.NewGuid().ToString())
.HtmlAttributes(new { role = "img" })
.DataSource(ds => ds
.Read("GetData", "Home")
)
)
Result

How to call ajax modalpop with dynamically created buttons?

I'm dynamically creating buttons with values from a database, and I have a modalpopup using ajax. I know that when using the popup I have to set a targetid, that's fine when its a predefined button. But how do you get the modalpopup to recognize a target when it dynamically created without having to use stringbuilder and rebuild a modalpopup on an eventhandler, and if I'm left to using stringbuilder then how do I call that when its created?
This is the code for the buttons
button.ID = Convert.ToString(myID);
button.Text = myStr;
button.PostBackUrl = "~/WebForm2.aspx?SubjectID=" + myID;
button.CssClass = "DynamicButtonOverlay";
This is the modalpopup
<asp:Panel ID="MyPanel" runat="server" CssClass="myModalPopup">
<table style="width:100%;">
<tr>
<td>Select News</td>
</tr>
<tr>
<td>
<asp:DropDownList ID="ddNewsToDelete" runat="server" CssClass="form-control"></asp:DropDownList>
</td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td>
<asp:Button ID="btnDeleteNews" runat="server" Text="Radera" CssClass="btn btn-danger pull-left" OnClick="btnDeleteNews_Click" CausesValidation="False" />
<asp:Button ID="btnClose" runat="server" Text="Close" class="btn btn-success pull-right" />
</td>
</tr>
</table>
</asp:Panel>
<asp:ModalPopupExtender ID="ModalPopupExtender1" runat="server" PopupControlID="MyPanel" BackgroundCssClass="myModalBackground" TargetControlID="Submit1" OkControlID="btnClose"></asp:ModalPopupExtender>
This is the code generating the buttons..
test.GetSubjects();
int subjectid = 0;
// Current row count.
int rowCtr;// = 0;
// Total number of cells per row (columns).
int cellCtr;
// Current cell counter.
int cellCnt;
//count number of rows in dataset
int rN = test.dsSubjects.Tables[0].Rows.Count;
cellCnt = 4;
for (rowCtr = 1; rowCtr <= rN; rowCtr++)
{
// Create a new row and add it to the table.
TableRow tRow = new TableRow();
Table1.Rows.Add(tRow);
for (cellCtr = 1; cellCtr <= 4; cellCtr++)
{
//
Button button = new Button();
//
HyperLink link = new HyperLink();
// Create a new cell and add it to the row.
TableCell tCell = new TableCell();
/* If the rowcounter is equal to the record numbers
* then it has to break because if not it will throw an error
* saying that there is no row at ending position */
if (rowCtr == rN)
break;
string myStr = test.dsSubjects.Tables[0].Rows[rowCtr - 1]["SubjectName"].ToString();
int myID = Convert.ToInt32(test.dsSubjects.Tables[0].Rows[rowCtr - 1]["SubjectID"].ToString());
button.ID = Convert.ToString(myID);
button.Text = myStr;
button.PostBackUrl = "~/WebForm2.aspx?SubjectID=" + myID;
button.CssClass = "DynamicButtonOverlay";
tCell.Controls.Add(button);
tCell.CssClass = "DynamicButtonOverlay";
tRow.Cells.Add(tCell);
rowCtr++;
/* If the cellcount is 3 then it needs to break, if not then
* you'll miss every 4rth record, don't know why. But this works */
if (cellCtr == 4)
{
rowCtr = rowCtr - 1;
break;
}
}
}

Razor View dynamic table rows

I want have a table in my view that is going to put 3 elements from my Model in each row. So the way I was going to do this is to loop through the model and inside of the foreach loop do a check on a count variable I have set up. If count mod 3 == 0 I would do something like </tr><tr> to start a new row. This isn't working the way I want it to because I would have a } following the <tr>. So basically my question is, how would I create a dynamic table inside of a razor view based on the elements in the model where each row has 3 items?
#{
int count = 0;
<div>
<table>
<tr>
#foreach (var drawing in Model)
{
<td style="width:240px;margin-left:30px; margin-right:30px;">
<img src="#Url.Action("GetImage", "Home", new { id = drawing.drw_ID })" alt="drawing" />
</td>
count++;
if(count%3==0)
{
</tr>
<tr>
}
}
</tr>
</table>
</div>
}
Maybe there is a much easier way of doing this that I am not thinking of
How about using two loops - this will make your document be setup much more nicely and make it a bit more readable. Also, it takes care of the problems that occur if the number of rows is not divisible by three:
<div>
<table>
#for(int i = 0; i <= (Model.Count - 1) / 3; ++i) {
<tr>
for(int j = 0; j < 3 && i + j < Model.Count; ++j) {
<td style="width:240px;margin-left:30px; margin-right:30px;">
<img src="#Url.Action("GetImage", "Home", new { id = Model[i + j].drw_ID })" alt="drawing" />
</td>
}
</tr>
}
</table>
</div>
Edited to reflect your pasted code. Note, this assumes the model implements IList or an array
Maybee this is the solution you are looking for works for me
#{
int count = 0;
**
var tr = new HtmlString("<tr>");
var trclose = new HtmlString("</tr>");
**
<div>
<table>
<tr>
#foreach (var drawing in Model)
{
<td style="width:240px;margin-left:30px; margin-right:30px;">
<img src="#Url.Action("GetImage", "Home", new { id = drawing.drw_ID })" alt="drawing" />
</td>
count++;
if(count%3==0)
{
**
trclose
tr
**
}
}
</tr>
</table>
</div>
}
Check this out, this should work for you !!!
<h2>Index</h2>
<table>
<tr>
#{
var index = 0;
}
#foreach (int num in Model)
{
if ((index % 10) == 0)
{
#Html.Raw("</tr>");
#Html.Raw("<tr>");
}
<td>
<h2>#num</h2>
</td>
index++;
}
</tr>
</table>
The #christian solution worked for me.I was not sure of "trclose" and "tr" hence posting here the solution that worked for me in razor view.
<table>
<tr><td><input type="checkbox" id="chkAssetCategories" /> SELECT ALL</td></tr>
<tr>
#{
var count=0;
foreach (var item in Model.AssetCategories)
{
<td><input type="checkbox" class = "Catgories" id='#item.ID' value ='#item.ID' /><label>#item.Name</label></td>
if (count%5 == 0)
{
#:</tr><tr>
}
count++;
}
}
</table>
#{ int counter = 0;}
<div>
<table>
#for(int i = 0; i <= (Model.Count - 1) / 3; ++i) {
<tr>
for(int j = 0; j < 3; ++j) {
<td style="width:240px;margin-left:30px; margin-right:30px;">
#Model[counter]
</td>
counter++;
}
</tr>
}
</table>
</div>

Categories

Resources