2

I have been stuck on this for some time now; I'm using ASP.NET MVC 4 and C# for a web application. I read in an Excel file from my controller, and I have a List of all the cells which I send back to my view. This is what I'm using:

<table>
@foreach (var item in ViewBag.range)
{ 
    <tr>
    @for (int i = 0; i < 6; i++) 
    {
        <td>
            <input style="width:50px;" value=@item />
        </td>
    }
    </tr>
}
</table>

Basically, I have 6 columns in Excel. I am trying to recreate the Excel in my view. But there is something wrong with my for loop, it's doing each cell 6 times.

Can anyone help please?

2 Answers 2

3

It does that because you tell it to in the for loop. Perhaps you should remove it.

<table>
 <tr>
  @foreach (var item in ViewBag.range)
  { 

    <td>
        <input style="width:50px;" value=@item />
    </td>

  }
 </tr>
</table>

EDIT

This will place the items inside of range into rows which have 6 columns each.

@{
 int total = 0; 
}

<table>
  @foreach (var item in ViewBag.range)
  { 
    if( total % 6 == 0 ){
        @:<tr>
    }
    <td>
        <input style="width:50px;" value=@item />
    </td>
    if( total+1 % 7 == 0 ){
        @:</tr>
    }
    total++;
  }
</table>
Sign up to request clarification or add additional context in comments.

4 Comments

Im trying to get 6 <td> 's in a table row, then i want it to go on next row. how can I do this?
@archie - I guess it depends on the data structure. The code above assumes there are 6 items in ViewBag.range. Based on that assumption, it will make 6 td elements. What is in range?
range is cells A1 to F29 in my excel sheet, so 6 columns
so in essence, theres 174 items in the loop, and i want to put them into rows of 6 elements in each row
0

Since I dont have enough information about range....I did the following with assumption ; modify and use it

 @{var counter=0}
    <table>
          <tr>
    @foreach (var item in ViewBag.range)
    { 
         counter++;
        <td>
            <input style="width:50px;" value=@item />
        </td>
         if(counter%6==0)
         {
           @:</tr>
            if(counter<ViewBag.range.Count)
            {
             @:<tr>
               }
         }

    }
    </table>

4 Comments

no thats not what I am trying to do, I want the Viewbag to loop through and get the first 6 values in a row, then loop through and get the another 6 values in the second row and so on..
In that case use a variable counter and increment it every time you add a column, if the count%6==0 , that is the time to close the old row and create a new one
thanks, could you please provide me a sample of how to do it?
Can you tell me strictly what is in range?

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.