0

I have this foreach code in my View in MVC4:

@foreach (var row in Model.Variables)
{
 <td>@row.Variable1.FirstOrDefault()</td>
 <td>@row.Variable2.FirstOrDefault()</td>  
}

Now I whant to write in each row number (sequential number).

I have try with this code:

@if (Model.Spremenljivke != null)
{
    int i = 0;
    foreach (var row in Model.Spremenljivke)
    {
        <tr align="center">
            <td>@i</td>
            <td>@row.Internal.First()</td>
            <td>@row.Exchangetimestamp.Add(Model.TimeZone.BaseUtcOffset)</td>
            <td>@row.Order.First()</td>
            <td>@row.MsgT.First()</td>
            <td>@row.Exchangetimestamp2.Add(Model.TimeZone.BaseUtcOffset)</td>
            i++;
        </tr>

        <tr><td colspan="7"><hr/></td></tr>

    }
}

Problem is that returns this:

i++;i++;i++ ...
Column i
0
0
0
0
...
4
  • Why you don't do the same thing done in seconth example? Simple declare var i = 0; i++ and print i each time. Commented Jun 17, 2014 at 7:17
  • If I understand you correctly, I have done this: before Foreach I have write var i = 0; then in <td>@i++</td> ? Commented Jun 17, 2014 at 7:24
  • Yes, I think this can be a good solution (if I understand your question). Commented Jun 17, 2014 at 7:29
  • I have try this and in <td> returns me: 0++ Commented Jun 17, 2014 at 7:31

1 Answer 1

1

I'l try answer your question with your example modified:

@{ var i  = 0; }
@foreach (var row in Model.Variables)
{
 <td>@i.ToString()</td>
 <td>@row.Variable1.FirstOrDefault()</td>
 <td>@row.Variable2.FirstOrDefault()</td>  
 @i++;
}

I've added var necessary to increment and show row num. You can write directly "i++" because you are in foreach statement managed by razord and @ is not necessary.

I hope this can help you.

Sign up to request clarification or add additional context in comments.

6 Comments

:( it does not work, it puts 0 in each row and i++ as text above table in one row (not in table), something like this: i++;i++;i++;... but so many time as I have rows in my table (15).
Do you think that is problem in my Variables, because they are multivalued, it meany that tey can be zero or some value? That is why returns me only zeros?
Sorry, but the problem is too strange. I've tested the foreach using a standard array (String), i is displayed correctly.
Do you think that problem is in Model.Variables? Because I am returning a group value from controler to Model.Variables. But, still, this should not be problem.
Please, Add @ before i var name (this will be: @i++ and not i++).
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.