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'>
Related
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
I have a view with 1700 records. I want to paginate them using ajax to make page load lighter. I am able to do paging and bring set of new records everytime based on the page selected.
The Problem
I am showing only 10 indexes in page-bottom, the page selected as well as 4 to the left and 5 to the right. Now I need CurrentPage value which I send everytime from jQuery/ajax to controller which I get as a ajax data parameter. The problem is in getting back Current page value persistent to view when the next page index I select. I always get the old value and not the last selected page value. I have even used ViewBag instead of tempData but no success.
View Code:
#model IEnumerable<UrCompedDAL.DBModels.SlotMachineModel>
<div class="my-properties">
<table id="tbl_slots" class="table no-margin" data-search="true" data-pagination="false">
<tbody class="orgTbody">
#foreach (var item in Model)
{
<tr>
//Code for Slot list
</tr>
}
</tbody>
</table>
<ul class="paging">
#{
int i = 1;
int pg = Convert.ToInt32(TempData["Current"]);
if (i > 0 || i == ViewBag.PageSize)
{
<li>
<<
</li>
}
if (pg < 6)
{
for (i = 1; i < 11; i++)
{
<li>
#i
</li>
}
}
else
{
for (i = pg - 4; i < pg; i++)
{
<li>
#i
</li>
}
for (i = pg; i < pg + 6; i++)
{
<li>
#i
</li>
}
}
if (i > 1 || i < ViewBag.PageSize)
{
<li>
>>
</li>
}
}
</ul>
</div>
<script>
$(document).ready(function () {
$('.lipaging').click(function () {
$("#loadingDiv").show();
$(this).addClass('active');
var pageThis = $(this).text();
var current = #TempData["Current"];
if (pageThis == '>>') {
pageThis = current +1;
}
if (pageThis == '<<') {
pageThis = current -1;
}
$.ajax({
type: 'get',
url: '#Url.Action("Index", "Game_SlotMachine")',
data: {
CurrentPage: pageThis
}
}).done(function (data) {
var startIndex = data.indexOf("<tbody");
var endIndex = data.indexOf("</tbody>");
var html = data.substring(startIndex, endIndex + 8);
$('#tbl_slots').html('');
$('#tbl_slots').html(html);
setTimeout(function () {
filter();
}, 300);
$("#loadingDiv").hide();
});
});
Controller Code:
public ActionResult Index(int id = 0, int CurrentPage = 1)
{
List<SlotMachineModel> slotmodel = new List<SlotMachineModel>();
slotmodel = UrCompedDAL.DataAccessor.Instance.GameAccessor.GetAllSlotMachines().ToList();
ViewBag.PageSize = slotmodel.Count / 10;
TempData["Current"] = CurrentPage;
slotmodel = slotmodel.Skip((CurrentPage - 1) * 10).Take(10).ToList();
return View(slotmodel);
}
Please help.
Pack your model IEnumerable<UrCompedDAL.DBModels.SlotMachineModel> into other model and set your model as a property of new model. Pass this new model as a model for your view. You will be able to pass as many data from controller as you like.
The issue is that you're re-creating the whole view, but only updating the table from the result
var html = data.substring(startIndex, endIndex + 8);
$('#tbl_slots').html('');
$('#tbl_slots').html(html);
(you should also reconsider how you extract the table from the view and use a partial instead).
None of the ajax/2nd+ rendering of the paging ul is used and is "thrown away" each time.
You can either overwrite your ul in the same way as the table or update the paging element via javascript (probably the former).
Reusing the whole view (rather than a partialview), you'd get something like:
}).done(function (data) {
var html = $("<div/>").html(data);
$('#tbl_slots').html(html.find("#tbl_slots").html());
$('ul.paging').html(html.find("ul.paging").html());
I am trying to output a player's stats in a table. Not all players will have stats depending on the day. I have tried other ways and all are still complaining. Here is the code I have now:
<tbody>
#foreach(var player in #ViewBag.Roster){
int index = 0;
<tr>
<td>#player.Name, #player.TeamName #player.Position</td>
if(#ViewBag.Stats[index] == null){
<td>--</td>
<td>--</td>
<td>--</td>
<td>--</td>
}
else{
<td>#ViewBag.Stats[index].Points</td>
<td>#ViewBag.Stats[index].Rebounds</td>
<td>#ViewBag.Stats[index].Assists</td>
<td>#ViewBag.Stats[index].Turnovers</td>
}
</tr>
index++;
}
</tbody>
Exception Details: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: Cannot perform runtime binding on a null reference
Source Error:
Line 32: }
Line 33: else{
Line 34: #ViewBag.Stats[index].Points
Line 35: #ViewBag.Stats[index].Rebounds
Line 36: #ViewBag.Stats[index].Assists
OK I am posting the full answer here -
Try # before if(#ViewBag.Stats[index] == null){ and remove # from #ViewBag inside the if so that it look like this - #if(ViewBag.Stats[index] == null){
You are setting index = 0, inside foreach, so it is initialised in every loop. Initialise it outside foreach like this
var index = 0;
foreach ...
if you are facing problem for the scope try this -
#{
var index = 0;
foreach (....) {
.......
index++
}
}
if you want to keep track of the index, why dont you rewrite your loop as:
var obj = new string[] { "", "", "" };
for(var index = 0; index < obj.Length; index++)
{
var item = obj[index];
/* DO STUFF WITH ITEM */
}
foreach(var item in obj.Select((value, index) => new { index, value }))
{
/* DO STUFF WITH item.Value */
}
I tried both cases suggested above, but with no luck.
Then finally I had to initialize my ViewBag collection in the Controller's Index method itself.
So when I did something like this,
var stringArray = new string[10] { "", "", "", "", "", "", "", "", "", "" };
ViewBag.doc = stringArray;
it worked. (I had 10 elements. If they were more, had to do something else for initialization.)
My code on the view part is as follows now:
#for (var itm =0; itm< 10; itm++)
{
<div class="form-group">
<label asp-for="Documents[itm].doc"></label>
<input type="file" asp-for="Documents[itm].doc" />
#if (ViewBag.doc[itm] != "")
{<a asp-area="" asp-page="/wwwroot/CaseDocuments/#ViewBag.doc[itm]">#ViewBag.doc[itm]</a>
<label asp-for="Documents[itm].remove"></label>
#Html.CheckBoxFor(a => a.Documents[itm].remove)
}
</div>
<div class="form-group">
<label asp-for="Documents[itm].desc"></label>
<textarea asp-for="Documents[itm].desc" class="form-control" rows="3"></textarea>
</div>
}
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:)
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>