1 Replies - 1918 Views - Last Post: 15 November 2012 - 12:23 PM

#1 solomon201  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 27
  • Joined: 19-November 07

Problem with foreach loop in MVC 3 Razor View

Posted 14 November 2012 - 05:33 AM

I have a loop in my razor view as below

<div>
@foreach(var inmate in Model)
{
     @inmate.inmateid
      @inmate.inmateid
}
</div> 



My Model is an IEnumerable of inmates containing 2 inmate objects. But the result I am getting in my browser is

6
6
7
7

Instead of
6
7

Please can someone tell me why this is the case?

Thanks

This post has been edited by Martyr2: 15 November 2012 - 12:24 PM
Reason for edit:: Please use code tags in the future, thanks! :)

Is This A Good Question/Topic? 0
  • +

Replies To: Problem with foreach loop in MVC 3 Razor View

#2 Martyr2  Icon User is offline

  • Programming Theoretician
  • member icon

Reputation: 4332
  • View blog
  • Posts: 12,127
  • Joined: 18-April 07

Re: Problem with foreach loop in MVC 3 Razor View

Posted 15 November 2012 - 12:23 PM

Well because you print @inmate.inmateid twice in the loop. The loop is going to loop through each inmate. Delete one and you will see it will print the 6 and 7 as you want. Now if the inmate object contains members which are another type or another inmate object you will need to access them through the inmate object..

@foreach(var inmate in Model)
{
    @inmate.inmateid
    @inmate.memberInmate.inmateid // <-- if memberInmate was another inmate object as a member
}



But based on your code it is showing twice because you have two @inmate.inmateid being printed. :)
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1