Search code examples
asp.net-mvc-3viewfor-loopforeachviewdata

convert foreach-loop to for-loop for Viewdata["terr"] which is list of objects


I have a list of checkbox like:

<% foreach (var tobj in (ViewData["terr"] as List<Location>))
{ %>
   <input type="checkbox" name="terr" id="<%: tobj.Location_Id %>" value="<%: tobj.Location_Id %>" disabled="disabled"/> 
   <span id="<%: tobj.Location_Name %>"> <%: tobj.Location_Name %> </span>
   <br />
<% } %>

But I want to display 3 or 4 checkbox in one row. and for that I need to conver foreach to for loop. I am not able to achieve this. Hope anyone can help me in this.


Solution

  • Im not sure why you cannot accomplish what you need in the foreach loop though. If you updated your question with a bit more info we could probably help you debug the initial foreach loop. Also if your using MVC 3 i recommend the Razor view engine, the syntax is a lot nicer.

    The for loop equivalent:

    <% { var locations = (List<Location>)ViewData["terr"] } %>
    
    <% for (int i = 0; i < locations.Count(); i++)
    { %>
        <input type="checkbox" name="terr" id="<%: locations[i].Location_Id %>" value="<%: locations[i].Location_Id %>" disabled="disabled"/> 
        <span id="<%: locations[i].Location_Name %>"> <%: locations[i].Location_Name %> </span>
        <br />
    <% } %>