Appending variable in for loop to mvc4 razor helper - c#

I have a number of fields in my model which are named as such model.var_1, model.var_2, ... model.var_30.
I am trying to put these in a table so I am using a for loop as so.
<table>
<tr>
<th>Category</th>
<th>Description</th>
#for (int i = 1; i <= Model.Total; i++)
{
<th class="ali_day#(i)">Day #i</th>
}
</tr>
<tr>
<th>Intubated</th>
<th></th>
#for (int i = 1; i <= Model.Total; i++)
{
<th>#Html.EditorFor(model => model.var_#(i))
#Html.ValidationMessageFor(model => model.var_#(i))</th>
}
</tr>
</table>
However, var_#(i) doesn't seem to be valid. Is there a way to append this loop counter so I can get my variable name while using an html helper?

Use the editor helper overload that takes a string, that way you can use string concatenation to create the variable name.
#Html.Editor("var_" + i)
and the same for the validation message
#Html.ValidationMessage("var_" + i)

Related

Blazor dynamically generated table rows

I created an sample c# blazor (server-side) app to practice a little.
I try to generate table rows dynamically for a calendar but i run into a problem there.
<table class="table">
<thead>
<tr>
<th>Monday</th>
<th>Tuesday</th>
<th>Wednesday</th>
<th>Thursday</th>
<th>Friday</th>
<th>Saturday</th>
<th>Sunday</th>
</tr>
</thead>
<tbody>
<tr>
#* currentDateTimeValues is a list with DateTime objects *#
#foreach (var item in currentDateTimeValues)
{
#if (counter % 7 == 0 && counter > 0)
{
#:</tr><tr>
}
counter++;
<td>#item.ToString("dd.MM.yyyy")</td>
}
</tr>
</tbody>
</table>
After 7 cells a new row should be created but it doesn't. The cells go straight ahead without linebreak.
Maybe you guys have any idea.
UPDATE:
In the meantime I've created a workaround because I think that blazor can't handle the </tr><tr>
My currentDateTimeValues-List now contains week objects
<tbody>
#* currentDateTimeValues is a list with Week objects *#
#foreach (var week in currentDateTimeValues)
{
<tr>
<td>#week.Monday</td>
<td>#week.Tuesday</td>
<td>#week.Wednesday</td>
<td>#week.Thursday</td>
<td>#week.Friday</td>
<td>#week.Saturday</td>
<td>#week.Sunday</td>
</tr>
}
</tbody>
I think the solution you are trying isn't possible in Blazor at the moment. Why not use two loops to create the calendar. Something like:
#while (counter < currentDateTimeValues.Length)
{
<tr>
#{
var i = 0;
if (i < 7 && counter + i < currentDateTimeValues.Length)
{
<td>#currentDateTimeValues[counter + i].ToString("dd.MM.yyyy")</td>
i++;
}
}
</tr>
counter += 7;
}

Issue adding rows to DOM table on MVC4

I have a "DOM" list in MVC 4 using jQuery to add elements dynamically but at the moment of removing all the elements
The table no longer allows me to add more elements, I have tried to use length and comparisons but it does not work.
Am probably missing something obvious but can't see what it is. Any ideas?
Example
Here is my table code
<div><img src="~/Images/splus.png" alt="Add Product" style="border:0"/></div>
<table id="dataTable" border="0" cellpadding="0" cellspacing="0">
<thead>
<tr>
<th></th>
<th></th>
<th>Product</th>
<th>Quantity</th>
<th></th>
</tr>
</thead>
<tbody>
#if (Model != null && Model.Count > 0)
{
int j = 0;
int index = 1;
foreach (var i in Model)
{
<tr>
<td>#index</td>
<td>#Html.HiddenFor(a => a[j].SEQ_NO, new { id = "nrow", Value = index })</td>
<td>#Html.DropDownList("PRODUCTS", "Select Product")</td>
<td>#Html.TextBoxFor(a => a[j].QUANTITY)</td>
<td>
<img src="~/Images/sminus.png" alt="Add Product" style="border:0"/>
</td>
</tr>
index += 1;
j++;
}
}
</tbody>
</table>
Here is my jQuery Code when i click on Add New
$("#addNew").click(function (e) {
e.preventDefault();
var last = $('#dataTable>tbody>tr:last');
if (last.length > 0) {
var name = last.children().find('input,select')[0].name;
var index = Number(name.replace(/[^0-9]/gi, '')) + 1;
var tr = ('<tr>' + last.html().replace(/[0-9]+__/gi, index + '__') + '</tr>').replace(/\[[0-9]+\]+[.]/gi, '[' + index + '].');
numberRows($('#dataTable tbody').append(tr));
}
});
UPDATE:
Add "REMOVE CODE"
$(document).on('click', '#remove', function (e) {
e.preventDefault();
$(this).parent().parent().remove();
numberRows($('#dataTable tbody'));
});
Am probably missing something obvious but can't see what it is. Any ideas?
var name = last.children().find('input,select')[0].name;
This line of code requires one last child, which means after you removed the last under , the name will be undefined. In fact, the Add New function won’t even pass the if (last.length > 0) since when the last got removed, the last.length becomes 0.
You can debug in devtools, and will see:
BEFORE the last got removed:
AFTER the last got removed:
Thus, to fix this issue, the simplest solution is to not remove the last but hide it. Please check below code:
$(document).on('click', '#remove', function (e) {
e.preventDefault();
if ($('#dataTable>tbody>tr').length > 1) {
$(this).parent().parent().remove();
//numberRows($('#dataTable tbody'));
}
else {
$(this).parent().parent().hide();
}
});
Ps. Not sure what happens in numberRows() function so I commented it.

Autoincrement won't work inside foreach in a table

Right now I'm trying to add a feature to my table.
It's being done inside a cshtml C# MVC ASP.NET Enviroment.
#{
dt_Table = ds_Set.Tables[1];
foreach (System.Data.DataRow dr in dt_Table.Rows)
{
int autoincrement = 0;
string nombre = dr["Nombre"].ToString();
<tr>
<td align="center">#(autoincrement++)</td>
<td align="center">#nombre</td>
</tr>
}
}
How do I add auto increment or ++ to the value?
Right now like that it just prints "1" on each row of the table :(
How can I solve this?
The variable autoincrement is scoped to the foreach loop block so it is allocated and released each iteration. Declare the variable outside of the foreach loop (or you can use a for loop):
for( var i = 0; i < dt_Table.Rows.Count; ++i )
{
var dr = dt_Table.Rows[i];
var nombre = dr["Nombre"].ToString();
<tr>
<td align="center">#i</td>
<td align="center">#nombre</td>
</tr>
}
Thanks for the quick answer, can't believe I could't figure this out
#{
int autoincrement = 1;
dt_Table = ds_Set.Tables[1];
foreach (System.Data.DataRow dr in dt_Table.Rows)
{
string nombre = dr["Nombre"].ToString();
<tr>
<td align="center">#(autoincrement++)</td>
<td align="center">#nombre</td>
</tr>
}
}

How could I fetch a parameter from this MVC architecture?

I have this HTML page in an ASP .NET project, and I need to generate a pagination for a table of elements. Problem is, in the class architecture that's already in place, the only thing I can have for my model is an IEnumerable of a view model. The ONLY thing I would need is to fetch an integer value from either my controller or the view it returns. From that integer, that would represent the number of buttons needed to generate the pagination, I would create it, see HTML.
My controller generates the list of items and returns in the model it by doing a SQL Request that selects a certain amount of item from a certain offset, depending on my URL's parameters.
Here's the HTML, and what the code-behind in the controller would look like:
#model IEnumerable<ItemIndexViewModel>
<h2>#UiText.PageTitles.ITEM_LIST</h2>
<hr />
<div class="col-md-12">
<div class="col-md-9">
<table class="table" id="client-index">
<thead>
<tr>
<th class="green-table-head-1">
#Html.DisplayNameFor(model => model.Name)
</th>
<th class="green-table-head-1">
#Html.DisplayNameFor(model => model.Id)
</th>
</tr>
</thead>
<tbody>
#foreach (ItemViewModel item in Model)
{
#*Here, I have my table of items being generated*#
}
</tbody>
</table>
<div id="pagination">
<ul>
#for (int i = 0; i < [I need my int right here]; i++)
{
#*I will generate buttons here*#
}
</ul>
</div>
</div>
</div>
public virtual ActionResult Index()
{
int ownerId = _httpContext.GetUserOwnerId();
int amountPerPage = 0;
int pageIndex = 0;
Int32.TryParse(Request.QueryString["amountPerPage"], out amountPerPage);
Int32.TryParse(Request.QueryString["pageIndex"], out pageIndex);
if (amountPerPage <= 0)
{
amountPerPage = 10;
}
if (pageIndex <= 0)
{
pageIndex = 1;
}
List<Item> items = _itemRepository.GetByPage(pageIndex, amountPerPage).ToList();
// Make view models from the list of items
List<ItemIndexViewModel> itemIndexViewModels = Mapper.Map<List<ItemIndexViewModel>>(items);
// Create the buttons for the HTML
int totalAmount = _itemRepository.Count();
int totalPages = (Int32)Math.Ceiling(Decimal.Divide(totalAmount, amountPerPage));
// Set update the navigation trace
SetTraceRoot(MVC.Item.Index(), MVC.Item.ActionNames.Index);
return View(itemIndexViewModels.OrderBy(x => x.Name));
}
What would be a good way of generating a pagination? I'm looking for flexibility because this procedure will be implemented for more than one page and for more than one class of items. I've already tried a couple of things to no avail, like using a class to contain my list of view models and an integer for the number of pages needed to store them all.
You can use ViewBag or ViewData instance in controller action to provide paging value before returning view:
ViewBag.TotalPages = totalPages;
And pass its value to the for loop to generate pagination in view side:
#for (int i = 0; i < ViewBag.TotalPages; i++)
{
#* generate paging buttons *#
}
Usually ViewBag properties don't require type cast for simple types (numeric & string values), but ensure that the value is assigned to avoid return null.

Razor table create with nested data

At the moment I am working on razor view, where I'd like to create a table as follows:
<tbody>
<tr>
<td rowspan="5">data</td>
<td rowspan="5">data</td>
<td rowspan="5">data</td>
<td rowspan="5">data</td>
#for (int i = 0; i < Model.AvailableCodes.Count; i++)
{
<td>#Model.AvailableCodes[i]</td>
#if ((i % 6) == 0)
{
</tr><tr>
}
}
</tr>
</tbody>
But I am getting a parse error (Parser Error Message: The for block is missing a closing "}" character.), at the beginning of the #for... a bit clueless why. Any help is really appreciated.
When you are in the for you don't need to pre-fix with an # for the if.
Also in order to ouput un-balanced tags you can use #:
#for (int i = 0; i < Model.AvailableCodes.Count; i++)
{
<td>#Model.AvailableCodes[i]</td>
if ((i % 6) == 0)
{
#:</tr><tr>
}
}

Categories

Resources