How to repeat for loop when the record count is one in ViewBag?

1.1k Views Asked by At

I have ViewBag which can have a count of one or two. If the count is one then I want some set of Html to repeat else if the count is two then I want the loop to execute normally.

for(int i = 0; i < ViewBag.Address; i++)
{
    if(i== 0) {
         <b>Current Address</b>
    }
    else{
         <b>Permanent Address</b>
    }

    <input type="text" value="@ViewBag.Address[i].Addreess1" />
    <input type="text" value="@ViewBag.Address[i].Addreess1" />

    //I tried doing something like
    i =  ViewBag.Address.Count == 1 ? 0: 1;     
}

But here the loop keeps on repeating is there anyway to check if the count is one then repeat the loop again else continue rendering as per the items within ViewBag.

3

There are 3 best solutions below

0
On BEST ANSWER

Can't You just move this statement:

i =  ViewBag.Address.Count == 1 ? 0: 1;   

inside for loop like this?

for(int i=1;i==1; i=ViewBag.Address.Count == 1 ? 0: 1)   
0
On

Just in case if you are caring about the count-

var count = @Enumerable.Count(ViewBag.Address)

Then-

@if(count==2)

@if(count==1)

Rectifying the code-

   @{
     var count = Enumerable.Count(ViewBag.Address);
    }

 @foreach (var item in ViewBag.Address)
    {
       if (count == 2)
        {
          <b>Current Address</b>
        }
       else
        {
          <b>Permanent Address</b>
        }

       <input type="text" value="@item.Addreess1" />
       <input type="text" value="@item.Addreess1" />
     }
6
On

this may be is what you want:

@switch (ViewBag.address.Count)
{
    case 1:   // some set of Html to repeat
        @for (int i = 0; i < length; i++)
        {
            <span> some Html item</span>
        }
        break;
    default:  // loop executes normally
        foreach (var item in ViewBag.Address)
        {
            <b>@item.SomeProperty</b>
            <input type="text" value="@item.Addrees" />
        }
}