Search code examples
for-loopasp.net-mvc-4viewactionmodels

MVC passing data to view and looping


I am terribly confused with MVC.

I don't have any code to show because i don't know how to do it.

I have an object

public class Name()
{
  String name="balh"
  String something="blah blah"
  //this object works fine and doesn't look like this it has the appropriate get;set;
  //use this as just an example
  //please disregard this format
} 

Now i have a

List<Name> list;//this just holds all of my objects

I need them to be passed to the View

I keep seeing something about models but i don't see it declared anywhere

How do i loop in the view to create something like this

<div> object1 string</div>
<div> object2 string</div>
<div> object3 string</div>
<div> object4 string</div>
<div> object5 string</div>

Solution

  • Your view would look like this, assuming you use your list as the model:

    @model List<Name>
    
    @foreach(var item in Model) {
      <div> @item.name @item.something</div>
    }
    

    So your controller action method might be:

    public ViewResult Index() {
      // Somehow build list which is List<Name>
      return View(list);
    }
    

    EDIT: You seem very new, so I recommend trying this tutorial: http://www.asp.net/mvc/tutorials/getting-started-with-aspnet-mvc3/cs/intro-to-aspnet-mvc-3